0

I am trying to map a json response into a state, what I am trying to do is map all the children of this array no matter how many, as in skipping the first array and only show its children, here is what i tried to do

fetch(api).then((response) => {
  response.json()  .then((data) => {
    data.children.map( (menu) => {

      this.setState({
        mydata: menu
      })
}) console.log("test", this.state.mydata )})  
    });

this is what i receive from the api

  {
    "name": "Store 1",
    "children": [
      {
        "name": "Store 1",
        "children": [{},{}...]
      },
      {
        "name": "Store 2",
        "children": [{},{}...]
      }
    ]
  }

and this is how i want it stored in my state,

[
          {
            "name": "Store 1",
            "children": [{},{}...]
          },
          {
            "name": "Store 2",
            "children": [{},{}...]
          }
      ]
3
  • Invoking this.setState() in loop over the same key is the issue.. Commented Oct 20, 2019 at 3:45
  • my goal is to have them mapped and stored to a state, instead of storing it and then mapping it in the render return Commented Oct 20, 2019 at 3:47
  • I would suggest mapping your array and then setting it in state once. Commented Oct 20, 2019 at 3:48

1 Answer 1

1

there's no need to map it. You should just put it into state.

fetch(api)
 .then(response => response.json())
 .then(data => this.setState({
  myData: data.children
 }))
Sign up to request clarification or add additional context in comments.

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.