const data = useSelector(store.data);
const [name, setName] = useState(data && data.name ? data.name : "")
const getData = () => {
dispatch(action.getData()); // loads data in store
}
return <div>{name}</div>
it it rendering that name is "" since i disaptch is not done before setting state
how can i know when the dispatch() is done? / how to fix it
2
Answers
You don’t. Your selector will cause your component to re-render once the store slice changes. If you would include your reducer in this post, people could better guess whats going on here, but here is my guess:
Your slice does not have a initial value, so that your selector returns undefined on first render. When you render your div, you are trying to access a paramter on a undefined value, which will result in a TypeError… You can fix this by making sure data is never undefined (Passing an iniitial value in your slice) or by only rendering data.name when data is truthy…
I would like to point out that in the example you provided nothing will ever trigger your getData fn…
if you need to know when a dispatched action has been processed and the state has been updated, you can use the store.subscribe() method provided by Redux. This method allows you to subscribe to changes in the store, and it will be called every time an action is dispatched and the state is updated