0

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

3 Answers 3

1

You are setting only one message in the state. First one, then replacing it with the second:

then(data => {
    data.map(message => this.setState({messages:message}))
})

If you want both messages save both in the state and then show them in the render with a map:

then(data => this.setState({messages:data}))

Render:

render(){
    return(
      <div>
         {this.state.messages.map(message => <h1>{message}</h1>)}
      </div>
    )
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You are overriding the state value every time map setsState, if you use this instead, it should work

  componentDidMount(){
     fetch('http://127.0.0.1:8000/api/message/?format=json')
    .then(response =>response.json())
    .then(messages =>  this.setState({messages}))
  }

Comments

0

This should be as simple as:

data => {
    this.setState({messages:data})
}

you are calling setState twice, so the first message is overwritten by the second.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.