state = {
resposne: [{ id: null, sentMessage: "", receviedMessage: "" }],
};
this is my state object I am fetching data from an API:
/*CONSIDER ABOVE API CALL IS WORKING AS I AM RECEIVING DATA ALREADY*/
.then((response) => {
return response.json();
})
.then((data) => {
if (data) {
this.setState(
this.state.response.push({
id: data.id,
receivedMessage: data.choices[0].text,
sentMessage: message,
})
);
console.log(this.state);
}
}
I am able to receive data but don't no how to store it in state object. my final state object should be something like this: API RESPONSe
id:1a,
sentMessage:"hello",
receviedMessage:"Hey,How are you"
/*state should be*/
state={
response:[{id:"1a",sentMessage:"hello",receviedMessage:"Hey,How are you"}]}
FOR NEXT FRAME API RESPONSe
id:1b,
sentMessage:"new message",
receviedMessage:"this is new message"
/*state should be*/
state={
response:[{id:1b,sentMessage:"new message",receviedMessage:"this is new message"},{id:"1a",sentMessage:"hello",receviedMessage:"Hey,How are you"}]}
AS YOU CAN SEE THIS LAST RESPONSE IS SET TO FIRST INDEX(I AM USING CLASS BASED COMPONENTS IN REACT NO HOOKS)
CONSOLE OUTPUT [0:{id:NULL,sentMessage:"",receivedMessage:""},1:{id:1b,sentMessage:"new message",receviedMessage:"this is new message"},{id:"1a",sentMessage:"hello",receviedMessage:"Hey,How are you"},response:[...]] HERE IS OUTPUT OF CONSOLE: with below soltion
this.setState({
response: [
...this.state.resposne,
{
id: data.id,
receivedMessage: data.choices[0].text,
sentMessage: message,
},
],
});
CodePudding user response:
The way you call the setState has not the required format (the piece of the state that is going to update)
Either of the following ways will work
Directly set the piece of the state object
this.setState({
response: [
...this.state.response,
{
id: data.id,
receivedMessage: data.choices[0].text,
sentMessage: message
}
]
});
Using the callback function of setState method
this.setState((prevState) => ({
...prevState,
response: [
...prevState.response,
{
id: data.id,
receivedMessage: data.choices[0].text,
sentMessage: message
}
]
}));