Skip to content

Instantly share code, notes, and snippets.

@lgh06
Forked from cant89/reactQuery_1.js
Created August 8, 2021 03:18
Show Gist options
  • Save lgh06/e8b459cc08edc1b01f02f50ddeb33878 to your computer and use it in GitHub Desktop.
Save lgh06/e8b459cc08edc1b01f02f50ddeb33878 to your computer and use it in GitHub Desktop.
const useFetch = (service) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState();
const [data, setData] = useState();
const fetchAPI = useCallback(async () => {
try {
const res = await fetch(service);
const json = await res.json();
setData(json);
} catch (err) {
setError(err);
}
setLoading(false);
}, [service]);
useEffect(() => {
fetchAPI();
}, [fetchAPI]);
return { data, error, loading };
};
const Todo = () => {
const { data, error, loading } = useFetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
useEffect(() => {
// eventually dispatch redux action
// if you need to store something
}, [data]);
if (error) {
return `Error: ${error} `;
}
if (loading) {
return "Loading...";
}
if (data) {
const { title, completed } = data;
return `${title} is ${!completed && "not "} completed`;
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment