Konstantinos Ks
Konstantinos Ks

Reputation: 79

React setState with data from mongoDB

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!

Upvotes: 0

Views: 1007

Answers (1)

wlecki
wlecki

Reputation: 360

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.

Upvotes: 1

Related Questions