This content originally appeared on DEV Community and was authored by Burak Boduroğlu
React Query is a library that provides a way to fetch, cache and update data in your React applications. It is a great library that can help you manage your data fetching in a more efficient way. In this post, we will take a look at how to use React Query to fetch data from an API and display it in a React component.
Installation
To get started with React Query, you need to install it in your project. You can do this by running the following command:
npm install react-query
or
yarn add react-query
After installing React Query, you should provide the QueryClientProvider
at the root of your application. This will allow you to use the useQuery
hook in your components. Here is an example of how you can set up the QueryClientProvider
in your application:
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();
const App = () => (
<QueryClientProvider client={queryClient}>
<div>{/* Your application components */}</div>
</QueryClientProvider>
);
export default App;
GET Data
Once you have installed React Query, you can start fetching data from an API. To do this, you need to create a query using the useQuery
hook. Here is an example of how you can fetch data from an API using React Query:
import { useQuery } from "react-query";
const fetchPosts = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
return data;
};
const Posts = () => {
const { data, isLoading, error } = useQuery("posts", fetchPosts);
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{data.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
};
export default Posts;
POST Data
React Query also provides a way to update data in your application. You can use the useMutation
hook to send a POST request to an API. Here is an example of how you can update data using React Query:
import { useMutation } from "react-query";
const createPost = async (newPost) => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newPost),
});
const data = await response.json();
return data;
};
const NewPost = () => {
const { mutate, isLoading, error } = useMutation(createPost);
const handleSubmit = (event) => {
event.preventDefault();
const newPost = {
title: event.target.title.value,
body: event.target.body.value,
};
mutate(newPost);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="title" placeholder="Title" />
<textarea name="body" placeholder="Body" />
<button type="submit" disabled={isLoading}>
{isLoading ? "Loading..." : "Submit"}
</button>
{error && <div>Error: {error.message}</div>}
</form>
);
};
export default NewPost;
React Query vs useEffect
React Query is a great library that can help you manage your data fetching in a more efficient way. It provides a way to fetch, cache and update data in your React applications. With React Query, you can easily fetch data from an API and display it in your components. It also provides a way to update data in your application using the useMutation
hook. If you are using useEffect
to fetch data in your React application, you should consider using React Query instead. It can help you manage your data fetching in a more efficient way and provide a better user experience.
Same Example with useEffect
Here is an example of how you can fetch data from an API using useEffect
:
import { useEffect, useState } from "react";
const Posts = () => {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchPosts = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const data = await response.json();
setPosts(data);
setIsLoading(false);
} catch (error) {
setError(error);
setIsLoading(false);
}
};
fetchPosts();
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{posts.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
};
export default Posts;
Summary
-
useQuery
hook is used to fetch data from an API. -
useMutation
hook is used to update data in your application. -
enable
option inuseQuery
hook is used to control when the query should be fetched.
Thank You
Thank you for reading this post. I hope you found it helpful. If you have any questions or feedback, please feel free to leave a comment below.
Follow me
This content originally appeared on DEV Community and was authored by Burak Boduroğlu
Burak Boduroğlu | Sciencx (2024-07-04T09:28:47+00:00) React Query Crash Post. Retrieved from https://www.scien.cx/2024/07/04/react-query-crash-post/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.