0

I have a weird situation. I have the following code which is not working.

const [result, setResult] = useState(props.fileNamesStatus.map((file, i) => {
    return {
        key: file.fileStatus
    }
}));

Strangely though, it works sometimes and sometimes it does not. I have used it in the JSX as follows:

I get the error Cannot read property 'key' of undefined

<ul className="in">
     {props.fileNamesStatus.map((file, i) => {
           console.log(result[i].key)     /// Cannot read property 'key' of undefined
    
     })}
</ul>
3
  • Why do you copy props to state and then use props in render? Why do you need state at all? Commented Oct 28, 2020 at 14:46
  • @AnastasiiaSolop I am building a toggle feature inside a map. The toggle works on click, I am setting up state to keep track of its state (enable/disable) Commented Oct 28, 2020 at 14:48
  • 1
    It is generally a pretty bad idea to copy props to state and keep them in sync. It always leads to complications and other bugs. You should avoid it whenever you can. But if you have to, make sure that you run useEffect and copy props to state whenever they change, I'll add an example in an answer Commented Oct 28, 2020 at 14:51

1 Answer 1

1

You need to add another useEffect hook:

useEffect(() => {
  if (props.fileNamesStatus && props.fileNamesStatus.length) {
    setResult(props.fileNamesStatus.map((file, i) => {
      return {
        key: file.fileStatus
      }
    }))
  }
}, [props.fileNamesStatus])

But even with this change there is a chance that in your render props and state will be out of sync, so you should add additional check console.log(result[i] ? result[i].key : 'out of sync')

Sign up to request clarification or add additional context in comments.

2 Comments

i console logged props.fileNamesStatus inside useEffect and it is empty. Although data does exist in it.
Is it a simple array of objects? How do you know that data is in it if console log shows it's empty?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.