×

React Js

The World's best Software Development Study Portal

UseEffectAPI Example

UseEffectAPI with Examples

Json Data : https://jsonplaceholder.typicode.com/albums/1/photos

(npm install bootstrap)

With the help of UseEffect you will tell react to remember the function you passed after rendering the compoment. UseEffect will call itself whenever you load the page.

Using Fetch

import React, { useState, useEffect } from 'react' const UseEffectAPI = () => { const [users, setUsers] = useState([]); const getUsers = async () => { const response = await fetch("https://jsonplaceholder.typicode.com/albums/1/photos"); setUsers(await response.json()); } useEffect(() => { getUsers(); }, []); return ( <> <h2>List of Github Users</h2> <div className="container-fluid mt-5"> <div className="row text-center"> { users.map((curElem) => { return ( <div className="col-10 col-md-4 mt-5" key={curElem.id}> <div className="card p-2"> <div className="d-flex align-items-center"> <div className="image"><img src={curElem.url} class="rounded" alt="img" width="155"/></div> <div className="ml-3 w-100"> <h4 className="mb-0 mt-0 textLeft">Deepak</h4> <span className="textLeft">{curElem.title}</span> <div className="p-2 mt-2 bg-primary d-flex justify-content-between rounded text-white stats"> <div className="d-flex flex-column"> <span className="articles">Articles</span><span className="number1">38</span></div> <div className="d-flex flex-column"> <span className="Followers">Followers</span><span className="number2">980</span></div> <div className="d-flex flex-column"> <span className="rating">Rating</span><span className="number3">8.9</span></div> </div> </div> </div> </div> </div> ) }) } </div> </div> </> ) } export default UseEffectAPI;

Output

------------------------------------------------------------------------------

UseEffectAPI Example 2

Json Data: https://api.opensea.io/api/v1/assets?format=json

import React, { useState, useEffect } from "react"; import axios from "axios"; const File = () => { const [users, setUsers] = useState([]); const getUsers = () => { const response = axios.get("https://api.opensea.io/api/v1/assets?format=json") .then((resp) => { console.log(resp); setUsers(resp.data.assets); }); }; useEffect(() => { getUsers(); }, []); return ( <div className="users"> <h2 className="heading">Data From API</h2> <div className="row"> { users.map((Data)=> { return( <div className="col-12 col-md-4 col-sm-6 mt-3 cards"> <div className="card mr-3 ml-2"> <img src={Data.image_url} className="card-img-top rounded image" width="300px" height="200px"/> <div className="card-body"> <div className="card-title"> <p className="card-name">{Data.name}</p> </div> <div className="card-text"> <p className="card-desc">{Data.description}</p> </div> </div> <div className="Button"> <p className="link">See More</p> <p className="link2">{Data.id}</p> </div> </div> </div> ) }) } </div> </div> ); }; export default File;

Output