I'm having a issue wrapping my head around how to extract the data from my backend api. The backend returns the data:
[{"id":1,"text":"What"},{"id":2,"text":"Hi"}]
My issue is that when using setState I only get the second object in the state when I want both.
Test.js:
import React, {Component} from 'react'
class Test extends Component{
constructor(){
super();
this.state = {
messages:{},
}
}
componentDidMount(){
fetch('http://127.0.0.1:8000/api/message/?format=json')
.then(response =>response.json())
.then(data => {
data.map(message => this.setState({messages:message}))
})
}
render(){
return(
<div>
<h1>
{console.log(this.state)}
</h1>
</div>
)
}
}
export default Test;
Instead of returning a state of :
message: {{"id":1,"text":"What"},
{"id":2,"text":"Hi"}
}
The console gives me three outputs:
{messages: {…}}
messages
:
{}
__proto__
:
Object
Test.js:25
{messages: {…}}
messages
:
{id: 1, text: "What"}
__proto__
:
Object
Test.js:25
{messages: {…}}
messages
:
{id: 2, text: "Hi"}
__proto__
:
Object