In my React codebase I've integrated Redux usign react-redux
and I'm using the useDispatch
hook to dispatch actions from my views. I just have one problem I don't have access to the updated values just after updating the store. Is there a way for me to wait for the state update to complete like await
or something like a callback where I can execute the other code?
This is how my code looks like:
import React from 'react';
import { useDispatch } from "react-redux";
import { setCore } from "../store/global";
// the value from the store is drilled down as props
export default function Home({ instance, core }) {
const dispatch = useDispatch();
const onConnect = async () => {
// core may have some value before but I want to clear
console.log(core); // prints the old value
await dispatch(setCore(null));
console.log(core); // Need to have null here
}
return (
<div>
<button onClick={onConnect}>Connect</button>
</div>
);
}
Dispatching by default is 100% synchronous. There's no need to wait for the dispatch itself.
However, waiting for the component's props to update is a completely different question. Given that code, core
will never update, because the definition of onConnect
has already captured the value of core
at the time the function was defined.
You may want to move that portion of the logic into a useEffect()
hook that will trigger when the value of core
has changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With