Skip to content

Latest commit

 

History

History
21 lines (18 loc) · 724 Bytes

04.setState-in-componentWillMount.md

File metadata and controls

21 lines (18 loc) · 724 Bytes

setState() in componentWillMount()

Avoid async initialization in componentWillMount()

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.

Make async calls for component initialization in componentDidMount instead of componentWillMount

function componentDidMount() {
  axios.get(`api/messages`)
    .then((result) => {
      const messages = result.data
      console.log("COMPONENT WILL Mount messages : ", messages);
      this.setState({
        messages: [...messages.content]
      })
    })
}