Created
July 3, 2025 12:23
-
-
Save av1v3k/72855b86b5d48d8a6d2b15a87e448bf6 to your computer and use it in GitHub Desktop.
custom hook for API call using react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //App.js | |
| import React from 'react'; | |
| import './style.css'; | |
| import { fetchUsers } from './custom_hook.js'; | |
| export default function App() { | |
| const { data, loading, error } = fetchUsers( | |
| 'https://jsonplaceholder.typicode.com/posts' | |
| ); | |
| if (loading) { | |
| return <div>{'loading'}</div>; | |
| } | |
| if (error) { | |
| return <div>{'Error'}</div>; | |
| } | |
| return ( | |
| <div> | |
| {data.map((item, idx) => ( | |
| <h3 key={idx}>{item.title}</h3> | |
| ))} | |
| </div> | |
| ); | |
| } | |
| //============================================================================================================ | |
| //custom_hook.js | |
| import React, { useState, useEffect } from 'react'; | |
| export const fetchUsers = (url) => { | |
| const [data, setData] = useState([]); | |
| const [error, setError] = useState(''); | |
| const [loading, setLoading] = useState(false); | |
| useEffect(() => { | |
| const fetchData = async () => { | |
| try { | |
| setLoading(true); | |
| const fetchposts = await fetch(url); | |
| const json = await fetchposts.json(); | |
| console.log('am i called?'); | |
| setData(json); | |
| } catch (error) { | |
| setError(error); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }; | |
| fetchData(); | |
| }, [url]); | |
| return { data, loading, error }; | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment