API call in Reactjs using fetch method

In this article we will see how to do a REST API call in a reactjs component using

  • fetch method
  • inside useEffect hook

Below is a sample code which demonstrates this.

Example:

import React, { useEffect } from 'react';

function App() {

// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(
(result) => {
console.log('result : ',result);
},
).catch((e) => console.log(e))
}, [])

return null
}

export default App;

Summary

In this article, we learnt how to call a rest api end point using fetch method in react useEffect hook.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !