I have a simple react function component A which gets data from redux store, once the data is updated from another component B the component A gets the updated data in initial variable declaration to useSelector, but when i use the same variable inside a method in that same react function component, it points to old data. Any idea what could be going on ? this component is bound to react-router path(/).
function Test(props) {
// Here it shows correct value.
const data= useSelector(getData);
const printData= () => {
// Points to old data with which the component was initially rendered with.
console.log(data);
};
return (
<Update
printData={printData}
/>
)
}
export default Test
Want correct data inside printData
2
Answers
Your
Update
component currently does not know that it needs to be re-rendered when thedata
state value changes because it is not being passed to that component as a prop, thus it keeps the stale value around from its previous render. Rather than (or in addition to) passing theprintData
function as a prop toUpdate
you need to pass indata
(or, preferably, simply use the selector insideUpdate
rather thanTest
).Its not exactly clear from your question what the cause of this issue is. But it seems to be that when the printData function is actually called from within the Update Component, the redux state has changed because of some other action you have performed.
It would be helpful for you use the redux devtool to see when the state changes.