Reputation: 556
I am trying to use ReactJS to store info provided by a backend API. My backend API returns a JSON object which contains:
"a": 123
"b": 345
"c": 0
The above object is stored under data from my backend API.
So now I would like to store these values in data separately in React State as follows:
this.state = {
first:'',
second: '',
third: '',
}
//ComponentDidMount happen here
.then(result => {
first: //result.data.data value "a":123 will be stored to State *First*
//and "b":345 will go to second and "c":0 to third
}
debugger;
})
What should I write for that part for storing information to state?
Upvotes: 0
Views: 334
Reputation: 2877
If you are fine with using 0, 1, 2
instead 'first', 'second', 'third'
, you can map through the values of the object and for each index store it in state
.then(result => Object.values(result).map((value, i) => this.setState({ [i]: value })))
Do notice that the actual keys in the state gonna be in a type of string, so you can access them like this.state['0']
Upvotes: 2
Reputation: 105
You may try
//ComponentDidMount happen here
.then(result => {
first.setState(result.data.data.a);
second.setState(result.data.data.b);
third.setState(result.data.data.c);
}
debugger;
})
Upvotes: 1