0

in my react app I have an array with the following structure as a state:

 data: {
   nodes: [{ id: 'Harry' }, { id: 'Sally' }, { id: 'Alice' }],
   links: [{ source: 'Harry', target: 'Sally' }, { source: 'Harry', target: 'Alice' }]
}

The data is initially empty. What I am trying to do, is to set the data state with data retrieved from my mongoDB. An example of the JSON from the database is this:

{
    "_id": {
        "$oid": "5c3a368dfb6fc0600bdedf49"
    },
    "nodes": [
        {
            "id": "root"
        },
        {
            "id": "input"
        },
        {
            "id": "component"
        }
    ],
    "links": [
        {
            "source": "component",
            "target": "root"
        },
        {
            "source": "input",
            "target": "root"
        }
    ]
}

Within the componentDidMount() in my react app I am fetching the data with the following code

    fetch('link')
    .then(data => json())
    .then((res) => {
      if (!res.success) this.setState({error: res.error});
    else console.log(res.data);
  }
});

Finally, this is what I am getting back form the console.log:

[…]

 0: {…}

_id: "5c3a368dfb6fc0600bdedf49"

 links: (2) […]

 0: Object { source: "component", target: "root" }

 1: Object { source: "input", target: "root" }

length: 2

 <prototype>: Array []

 nodes: (3) […]

 0: Object { id: "root" }

 1: Object { id: "input" }

 2: Object { id: "component" }

length: 3

 <prototype>: Array []

 <prototype>: Object { … }

length: 1

So, I haven't figured out how to set the state with these data and put it in the data state with the proper structure. Any advice will be helpful, thank you!

1 Answer 1

1

Will the backend always return links and nodes arrays?
If yes, you can do:

this.setState({
    data: {
        nodes: res.data.nodes,
        links: res.data.links,
    }
});

If not, you have to check if nodes or links are returned from the api call and update the state respectively only for the data that has been returned.

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

3 Comments

Thank you a lot for your answer! When I am setting the state with res.data.nodes, I get "undefined" returned. The problem seems to be solved when I use res.data[0].nodes. I believe this will not cause any problems in the future. Thank you again.
@KonstantinosKs - so it looks like your backend is returning an array of data - maybe it is something that can be changed so that you don't need to access the first index so you will be able to just go with res.data.nodes?
I will try if I can change the way the data is returned. If I find something I will post it here.

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.