skip to Main Content

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


  1. Your Update component currently does not know that it needs to be re-rendered when the data 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 the printData function as a prop to Update you need to pass in data (or, preferably, simply use the selector inside Update rather than Test).

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search