Open grafisaholic opened 2 years ago
Creating custom hook file with name useFetch.js:
import { useState, useEffect } from "react"; const useFetch = (url) => { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then((data) => setData(data)); }, [url]); return [data]; }; export default useFetch;
Using custom hook in index.js:
import ReactDOM from "react-dom/client"; import useFetch from "./useFetch"; const Home = () => { const [data] = useFetch("https://jsonplaceholder.typicode.com/todos"); return ( <> {data && data.map((item) => { return <p key={item.id}>{item.title}</p>; })} </> ); }; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Home />);
Creating custom hook file with name useFetch.js:
Using custom hook in index.js: