19
loading...
This website collects cookies to deliver better user experience
const baseUrl = 'https://jsonplaceholder.typicode.com';
const usePosts = () => {
const [data, setData] = useState();
useEffect(() => {
const fetchData = async () => {
const res = await fetch(`${baseUrl}/posts`);
const posts = await res.json();
setData(posts);
};
fetchData();
}, []);
return { data };
};
const usePosts = () => {
const [data, setData] = useState();
const [isLoading, setLoading] = useState(true);
const [error, setError] = useState();
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await fetch(`${baseUrl}/posts`);
const posts = await res.json();
setData(posts);
setLoading(false);
} catch (error) {
console.log(error);
setError(error);
setData([]);
setLoading(false);
}
};
fetchData();
}, []);
return { data, isLoading, error };
};
usePosts
hook using react-query. If you haven't used react-query before, you're in for a surprise.// hooks/hooks.js
const usePosts = () => {
const fetchData = async () => {
return fetch(`${baseUrl}/posts`).then((r) => r.json());
};
return useQuery('posts', fetchData);
};
usePost
hook.const usePost = (id) => {
const fetchData = async () => {
return fetch(`${baseUrl}/posts/${id}`).then((r) => r.json());
};
return useQuery(['post', id], fetchData);
};
// pages/index.js
import { useQueryClient } from 'react-query';
export default function Home() {
const queryClient = useQueryClient();
const reFetchPosts = () => {
queryClient.invalidateQueries('posts');
};
return (
<Container>
<Button onClick={reFetchPosts}>Re-fetch</Button>
{data.map((post) => {
//...
})}
</Container>
);
}