0

I am trying to fill an array with an array of objects that was returned from a axios request. However, the array is returned empty.

export default class Todo extends Component {
constructor(props){
    super(props)
    this.state = { description: '', list: [] }

    this.handleChange = this.handleChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)

    this.refresh();

}

    refresh() {
        axios.get(`${URL}?sort=-createdAt`)
            .then(resp => this.setState({...this.state, description: 'Qualquer valor', list: resp.data}))
            //.then(resp => console.log(resp.data))

            console.log(this.state.list)
    }

I initialize the array in the constructor (named "List") and then, following the refresh function, whcih is called as soon as the page loads, I receive the response of the axios request, and try to fill the "list" array with the data returned values, but it doesn't work.

Obs: I already guaranteed that the request is returning well and the "resp.data" contains the data that I want to push to the array named "list" (the response is returning an array of objects)

R_Dax
  • 706
  • 3
  • 10
  • 25
Leojbnv
  • 13
  • 4
  • 2
    the setState is async, you cant access updated state after update – Nikita Mazur Jun 01 '21 at 11:20
  • You don't need to do `...this.state`. React takes care of maintaining the state of all it's elements whenever we update any of the elements. In setState just update whatever you need to update. It should be `.then(resp => this.setState({description: 'Qualquer valor', list: resp.data}))` – Vivek Bani Jun 01 '21 at 11:23
  • The answer you are looking for is this: https://stackoverflow.com/a/41446620/8623549 – Bogdan Jun 01 '21 at 11:32

2 Answers2

0

If you call function from constructor and in that function try to update state than react will not throw warning and will not update state.

So instead of calling function in constructor, try to call function in componentDidMount like below and try to access updated state value in callback function:-

constructor(props){
    super(props)
    this.state = { description: '', list: [] }

    this.handleChange = this.handleChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
}

componentDidMount() {
  this.refresh();
}

  refresh() {
    axios.get(`${URL}?sort=-createdAt`).then(resp =>
      this.setState(
        {
          description: 'Qualquer valor',
          list: resp.data
        },
        () => {
          console.log(this.state.list);    // here this will print updated list
        }
      )
    );
  }

Priyank Kachhela
  • 2,517
  • 8
  • 16
0

The axios request call has to go in the componentDidMount life cycle hook, not the constructor.

Please refer to the documentation for more details: https://reactjs.org/docs/react-component.html#componentdidmount