Single event in React Redux app that integrates legacy library - reactjs

I have a React app using Redux to handle the overall state of the app that also integrates some legacy Javascript library to present a specific viewer (on a canvas). The legacy library manages for the viewer its own state (and I don't have access to it). I now have the case that one of my components need to trigger an event on the viewer in another component (e.g. reset the viewer using the legacy library).
I can think of two solutions:
Do a Redux state change (e.g. {reset: true}) that is provided to the viewer component via props. And after the viewer component reseted the viewer, it directly resets the state itself (e.g. `{reset: false}).
Bypass Redux and use some kind of PubSub pattern for those components to communicate directly to each other without any Redux state change.
Is there recommended way? What are the advantages/disadvantages? One downside of option 1 seems that it triggers a re-render when the state is updated the second time ({reset: false}).

Another way i have come up is by specifying the time at which it got reset.
If the time changes this will trigger a re-render.
on dispatch(reset())
Action:
reset(){
return({
type:constant.RE_RENDER,
payload: new Date().getTime()
})
}
STORE:
if(state.reset < action.payload){
return {
reset: action.payload
}
}
The view will get updated only once. Using another pub-sub system will add undue complications and bypassing redux pattern is not recommended.

Related

Where to put non-specific state properties in Redux Toolkit?

I want to use Redux Toolkit, but have global state properties that are not specific to a particular feature, such as "loading" and "errors". These two properties are updated when I make API requests concerning multiple features in my app. Should I put them in their own e.g. API reducer? Thanks
It is always better to have separate loading, errors for each api call or each component reducer.
you can think this way, what component is visible to the user at that moment and you want to show loading till the data comes from backend.
You only keep any state global and share when it will be used in another component.

Can I use state in components while using Redux or Redux store?

**Is it OK to Using a component state for just to handling form data, while the main data and other stuff of the application will be stored in the Redux store?
I don't want to use redux-form instead manually dispatch it to the reducers**
Redux comes into the picture when we want to manage the state across different component. It provides a centralize store where state of all the components are managed.
When talking about forms, in most cases form data is only limited to the component is which is being used. So, in that type of scenario there is no need to link them to centralized store using redux. A simple way is to store them in the component state and get it processed. Afterwards, you can store the output of that in redux store according to your needs.
It is okay to do that. You can keep a local state in the component. state = {} in class components, const [localState, setLocalState] = useState() for functional components.
Or you can use custom hooks for handling your local state needs. Check out useInput or useForm custom hooks that are developed by the community.
Yes of course. Some things go best in component state, some go best in a parent component, some go in Context, and some go in Redux. There is little use in putting everything in Redux, it just causes a lot of boilerplate and every component tries to update when the store changes.
You put things in Redux when different components that are at different places in the HTML tree use the same data, and it changes during the app's lifetime (things like the user's language don't change often and go in Context). You use it when you want to store your app's state to restore it later (which exact menus are currently open or closed is usually not that important) and when you want to keep track of state changing using the Redux dev tools.

when use redux, can I call api in container component?

I am very confused recently.
When I write redux, if I have to call api ,I will put an action to update reducer, the component just render the data from props
But recently I see my coworker just call api in container component and then update the component state.
He says if your data do not need to share with other component, you can call api in component, so you don't have to write so many code in actions and reducers.
I thought this is very convenient. For example: If I have a feature : When user click the button, I have to send an email.
This feature do not need to update store by reducer, just have to alert "send success"
So I can write this code in container component:
async onClick() {
// 1. call api
const {error, response} = await sendMail({email: this.state.email});
if (response){
// 2. alert success
this.setState({
modal: {
show: true,
}
});
}
}
But I don't know if this match redux's principle.
Can I call api directly in component if the state do not need to share with other component??
You can call api from dispatched actions or from React components: it is your choice to make. There is no mandatory rules here and it depends on what you want to do with your components:
When to use React states:
It is better to have smart component handling their own state because it ease the integration in external projects. Having a component that uses Redux means a project needs to add the requires reducers to use the component.
If a component handles information not required by any other components, use React state. It is often the case for information related to UI state.
When using Redux reduces:
If you need to test your component, prefer Redux because you'll be able to connect "test actions" to your component when testing them.
If you need to share a bundle of data through components, prefer Redux to mutualise information.
This question has been treated by Gaeron on Redux github repository if you want to have a look. He explains:
Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft. Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local). The rule of thumb is: do whatever is less awkward.
I suggest you have a look at classux

SPA + back button + form state

I am converting a jsp multi-page app(mpa) into a React single-page app (spa). In the mpa, the back button worked and the form retained its state.
In my new React app, the back button works but the form does not retain its state.
Question: is there a trick to make my form retain its state after "backing" to it (in an spa).
Here are the two solutions I came up with:
Encode the entire form state into the url. Then update the browser history with an updated url every time the form changes. But, this seems like a huge pain in the butt.
Modify the structure of my app such that the form in question (a React Component) stays mounted (and just use the css visibility or display property to show and hide). But, in a large app, leaving every page mounted in the DOM seems like it might lead to performance problems.
By the way, I am using popstate and the browser history api to achieve SPA behavior (i.e. i have rolled my own router) as described here.
Hopefully someone can propose a solution that is better than my two solutions. Thanks.
I ended up using something similar to Wylie Кулик's answer with a few changes:
I didn't want to switch to Redux for just this one use-case. So I used the component state of my top-level component (i.e. a component higher up the tree).
I cached the form's state on the form component's componentWillUnmount and restored the cached state on componentDidMount.
I passed the cached state as a prop from the higher component to the child component.
It ended up being a very small amount of code and is working like a charm so far.
Use Redux to have a state store which transcends any particular component. Then in your component, as part of the form submission process, dispatch an action with payload of all of the form data. This should be cached on state and then when the component is remounted by your navigation structure, it should have access to this cache via Reduxsconnectfunctions mapStateToProps method. You can repopulate your form from that.
It's not clear from your question whether or not you are submitting the form in the traditional old way. I would use e.preventDefault in the handler instead, and have all the form data on the component's state, this can be sent to Redux's state store as described above, and Ajaxed off with superagent or similar. At the same time it can be cached.
Redux: http://redux.js.org

Why would I never need to use subscribe in Redux?

If, in React, I can use connect to map state and dispatch to props, and the component I used connect on will auto-render when the Redux state (and hence props) change, why would I ever need to use subscribe?
You're talking about Redux and Redux-React (which provides the connect function, specifically for React components). Take a look at how Redux-React is implemented.
connect is just a React specific abstraction over subscribe.
What happens if you aren't using React? It's totally possible to use Redux with other frameworks or even just plain Javascript applications. In these cases, there needs to be a lower level mechanism for subscribing to changes in state.
They have also updated their documentation to speak to this regarding subscribe
It is a low-level API. Most likely, instead of using it directly, you'll use React (or other) bindings. If you commonly use the callback as a hook to react to state changes, you might want to write a custom observeStore utility. The Store is also an Observable, so you can subscribe to changes with libraries like RxJS.

Resources