Custom useFetch Hook
ReactJS
Hard
8 views
Problem Description
Create a useFetch hook that returns loading/error/data.
Output Format
Render a React component.
Constraints
Fetch in effect and protect against unmount.
Official Solution
import React, { useEffect, useState } from 'react';
function useFetch(url) {
const [state, setState] = useState({ loading: true, error: '', data: null });
useEffect(() => {
let cancelled = false;
async function run() {
setState({ loading: true, error: '', data: null });
try {
const res = await fetch(url);
const json = await res.json();
if (!cancelled) setState({ loading: false, error: '', data: json });
} catch (e) {
if (!cancelled) setState({ loading: false, error: String(e.message || e), data: null });
}
}
run();
return () => { cancelled = true; };
}, [url]);
return state;
}
export default function App() {
const { loading, error, data } = useFetch('https://jsonplaceholder.typicode.com/todos/1');
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode fetch hook</h2>
{loading ? <div>Loading...</div> : null}
{error ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
{data ? <pre style={{ background: '#f6f8fa', padding: 12, borderRadius: 14 }}>{JSON.stringify(data, null, 2)}</pre> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!