2

I have a component that gets data as prop from parent component via react router Link component like this:

<Link to={{pathname: "/cv", state:cvData }}>Next</Link>

And the CV component in that "/cv" path gets that state. But in the JSX of the CV-component, I cannot access data in that state. The code is like this:

const [cvData, setCvData] = useState(props.state)
useEffect(() => {
    setCvData(props.cvData)
    console.log(cvData)
}, [])

The output of that console.log is first undefined and then the data. But even though it logs the right data, the JSX part throws error of 'cannot read property x of undefined'.

2 Answers2

2

That's because at some point in the beginning your data is first undefined,you can add a simple check condition before using it,for example:

return(
  <div>
    { cvData && cvData.x ? <div>display your cvData</div> : null }
  </div>
)
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
Sakshi
  • 1,464
  • 2
  • 8
  • 15
0

By default,useEffect() runs both after the first render and after every DOM update. Setting the state will trigger the React to re-render and but before re-render it will update the DOM and remembers the state variable value and it will use it after re-render.

During the first render your props.state is undefined.

After the first render, useEffect() will run and it will set the state and remembers it. You have console.log inside the effect which will print an undefined state.

Now, React will update the DOM, when you trying to access the undefined state it will throw an error "cannot read property x of undefined".

In my opinion, we shouldn't use setState inside the useEffect.

Subrato Pattanaik
  • 5,331
  • 6
  • 21
  • 52