40
loading...
This website collects cookies to deliver better user experience
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();
const App = () => {
return <QueryClientProvider client={queryClient}>
<Posts />
</QueryClientProvider>
}
import { useQuery } from "react-query";
const Posts = () => {
const { isLoading, error, data } = useQuery('repoData', () =>
fetch('https://jsonplaceholder.typicode.com/posts').then(res =>
res.json()
)
)
if (isLoading) return 'Please wait...'
if (error) return 'Error' + error.message
return (
<div>
<h1> Posts of the Day </h1>
{ data.map(post => <h1 key={post.id}> {post.title} </h1>) }
</div>
});
}
useQuery
hook that take care of fetching data from the server. Something like GET
method. Notice how this hook abstract the loading
and error
handling part.We didn't require to use try catch
block here.
Axios
here. Cache Memory
.useQueryClient
hook from react-query
. Cache Memory
. That will syncs your data automatically without dispatching any actions or updating any states manually. This will be really helpful for a complex React Application.useMutation
library to mutate data on server.import { useMutation, useQueryClient } from "react-query";
const NewPost = () => {
const client = useQueryClient();
const { mutate, isLoading } = useMutation(async (newPost) => {
return await Axios.post("https://myblog.app/new", {...newPost}, {
// register all the callbacks,
onMutate: () => {
// this will be called when you invoke mutation method
// ie like temporary showing blog
},
onError: (error) => {
// this will be called when your API request get failed.
},
onSettled: () => {
// this will work either way. (Success, Fail)
},
onSuccess: (response) => {
// this will be called when your API request get
// executed successfully.
client.invalidateQueries("posts"); // will refetch posts
}
});
})
const newPost = () => {
// add new post
mutate({ id: `temp-name`, title: "My Blog", content: "The content goes here..." });
}
}
react-query
library. You can prefer documentation for that. react-query
or not.