Skip to content

Instantly share code, notes, and snippets.

@av1v3k
Created July 3, 2025 12:23
Show Gist options
  • Select an option

  • Save av1v3k/72855b86b5d48d8a6d2b15a87e448bf6 to your computer and use it in GitHub Desktop.

Select an option

Save av1v3k/72855b86b5d48d8a6d2b15a87e448bf6 to your computer and use it in GitHub Desktop.
custom hook for API call using react
//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