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 plete 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>
);
}
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 plete 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>
);
}
Share
Improve this question
asked Nov 12, 2019 at 20:10
aksaks
9,49112 gold badges52 silver badges81 bronze badges
1 Answer
Reset to default 14Dispatching by default is 100% synchronous. There's no need to wait for the dispatch itself.
However, waiting for the ponent's props to update is a pletely 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.