React useEffect fetching API

Shubham Tiwari - Jul 20 '21 - - Dev Community

Hello everyone today i will show you how to fetch API in react js using 'useEffect'.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

What does useEffect do?
By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.

Lets get dive into the code now-

First we will import the required modules

import React,{useState,useEffect} from 'react'
/*here we have imported the useState to change the state of the
 data when the data gets update on the end point and useEffect
 is used to fetch the data from the api 
and it will run on every render
*/
Enter fullscreen mode Exit fullscreen mode

Here we are fetching data from a fake api called jsonPlacenholder api which gives us data of a todo list with 'pending' and 'completed' status

 const [todos, setTodos] = useState([]);
//useState is set to an empty arraya and later 
//we will fetch the data from the end point 
//and will store in the 'todos' array
Enter fullscreen mode Exit fullscreen mode

useEffect -

 useEffect(() => {
    fetch('http://jsonplaceholder.typicode.com/todos')
    .then(res => res.json())
    .then((data) => {
      setTodos(data)
      console.log(todos)
    })
 }, [todos]);
Enter fullscreen mode Exit fullscreen mode
  1. fetch is used to fetch the api from end point
  2. Then we set the state of todo to the data we have fetched from the API.
  3. In the last line of it [todos] is the dependency on which useEffect depends on.

Then we map the data using map function

{todos.map((todo) => (
             <div className="card bg-dark text-light my-3">
               <div className="card-body">
                 <h5 className="card-title">{todo.title}</h5>
                    <h6 className="card-subtitle mb-2 text-muted">
                      { todo.completed &&
                      <span>
                        Completed
                      </span>
                      }
                      { !todo.completed &&
                      <span>
                        Pending
                       </span>
                      }              
                   </h6>
              </div>
           </div>
          ))}
Enter fullscreen mode Exit fullscreen mode

Full source code -

import React,{useState,useEffect} from 'react'
import Fade from 'react-reveal/Fade'
import {Navbar,NavbarBrand,NavbarToggler,Nav,NavItem,NavLink,Collapse} from 'reactstrap';
import './App.css'
function App() {

  const[toggle,setToggle] = useState(false);
  const isToggle = () => setToggle(!toggle);
  const [todos, setTodos] = useState([])

  useEffect(() => {
    fetch('http://jsonplaceholder.typicode.com/todos')
    .then(res => res.json())
    .then((data) => {
      setTodos(data)
      console.log(todos)
    })
    .catch(console.log)
    }, [todos])

  return (
    <div className="">    
    <h1 className="text-primary text-center display-4 mb-5">React fetch api using useEffect</h1>
      <div className="text-center" style={{display:"block",width:"50%",margin:"0 auto"}}>
        <div style={{display:"flex",flexDirection:"column",justifyContent:"center",justifyItems:"center",width:"100%"}}>
          {todos.map((todo) => (
             <div className="card bg-dark text-light my-3">
             <div className="card-body">
               <h5 className="card-title">{todo.title}</h5>
               <h6 className="card-subtitle mb-2 text-muted">
               { todo.completed &&
                 <span>
                 Completed
                 </span>
               }
               { !todo.completed &&
                 <span>
                   Pending
                 </span>
               }              
               </h6>
             </div>
           </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Here is the Output-

Screenshot (5)
I am newbie developer.So , if you find any mistake regarding any post Please highlight it
THANK YOU FOR READING THIS POST.

NOTE- In the example , we have bootstrap classes so , use bootstrap cdn or install and import it using npm or yarn package manager

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player