'I am trying to set data in state everytime on first index for react in array of object
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,
},
],
});
Solution 1:[1]
In the thread panel, you can resume the execution of the other threads.
If you want that the other threads does not stop, I don't know a way of doing it sadly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kuinox |

