DEV Community

Cover image for Most essential React patterns - api call
arfa
arfa

Posted on

Most essential React patterns - api call

Calling APIs is one of the vital parts of each web app, so it's essential to know how to do it in the best way. for those APIs that you fetch some data from a server
probably, you need to save those data on a state, and this cause rerender as well, so clearly you should care about when calling them and fetch their result

for most scenarios calling them inside an useEffect is a good choice but make sure that pass an empty array as the second argument to let useEffect execute once exactly like component did mount

useEffect(() => {
  fetch('api/sms')
    .then(result => {
      const sms = result.data
      console.log('COMPONENT WILL Mount messages : ', sms)
      this.setState({sms: [...sms.content]})
    })
}, [])
Enter fullscreen mode Exit fullscreen mode

so if you are dealing with class components, compoentDidMount would be your choice

function componentDidMount() {
  fetch('api/sms')
    .then(result => {
      const sms = result.data
      console.log('COMPONENT WILL Mount messages : ', sms)
      this.setState({sms: [...sms.content]})
    })
}
Enter fullscreen mode Exit fullscreen mode

written based on this article

Top comments (0)