简体   繁体   中英

Fill an array with an object (using setState)

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)

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
        }
      )
    );
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM