1

I have an object like so:

    {
      "id": 1,
      "name": "car",
      "colors": ["white", "black"]
    }

I put my object into data using useState.
When i try data.name the result is "car"
When i try data.colors the result is "whiteblack"
But when i try mapping over the colors using:

{data.colors.map((color, i) =>
  <span key={i} >{color}</span>
)} 

Ill get TypeError: Cannot read property 'map' of undefined
What am I missing?

3
  • can you show how you initialized data Commented Oct 7, 2020 at 10:26
  • where are you mapping data.colors data? Commented Oct 7, 2020 at 10:30
  • I suppose your data gets into state asynchronously? And you try to map through it in the render, which happens before the data is loaded. If yes, this is causing the error. If no, please share your component logic here. Commented Oct 7, 2020 at 10:31

2 Answers 2

2

One likely reason is that you try to map over data before data is loaded. For example, if you initiate a fetch call to some resource when a component is loaded but also map over the returned object at the same time. In that case, data would be undefined.

A simple fix would be to check if data is undefined before mapping over it.

{data && data.colors.map((color, i) =>
  <span key={i} >{color}</span>
)} 
Sign up to request clarification or add additional context in comments.

1 Comment

I completely forgot I can check if data is already available. Thanks
0

May be it's state initializing issue, you could do something like this:

const [state, setState] = useState({
      "id": "",
      "name": "",
      "colors": []
    });

useEffect(() => setState({
      "id": 1,
      "name": "car",
      "colors": ["white", "black"]
    }), []);

This will fix your map of undefined issue.

Comments

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.