In today modern web development, HTTP request is very crucial for applications, so the need for efficient data management becomes increasingly critical. This article will expose you to Tanstack, it`s key features and how to get started.
Tanstack
Tanstack is an amazing library for data management in applications, it addresses data management issues for asynchronous data operations. It helps developers to carryout HTTP requests easily.
What is HTTP request?
HTTP request (Hypertext Transfer Protocol) is usually a message sent by a browser to the server to initiate a communication and to request data or actions. HTTP is very important to the World Wide Web, it is a fundamental part of the web. Without it, we might not have applications.
HTTP request allows frontend applications to perform GET, POST, PUT, DELETE, PATCH etc actions on the server through an endpoint.
Benefits of using Tanstack
Caching and Data Synchronization: With built-in caching mechanisms, tanstack optimizes the performance of your application by storing data locally. This reduces the number of requests, which will make your application to be much faster.
Optimistic Updates: Tanstack facilitates optimistic updates, this enables developers to update the UI accordingly. It has amazing states like, the error, isLoading. You can use these to conditionally render a loading state while the data is loading.
Automatic Pagination and Infinite Loading: Handling large datasets becomes effortless with tanstack’s support for automatic pagination and infinite loading. Developers can seamlessly fetch and display data in chunks, enhancing application performance and user experience.
How to use Tanstack
First, we have to install tanstack by running npm i react-query
on our terminal.
We have to inject the QueryClientProvider in our application so that we can be able to use Tanstack. We will also provide it with the queryClient as a prop. You can create this in the index.js file of your application.
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import Nav from "./Nav";
import { BrowserRouter } from "react-router-dom";
import { QueryClientProvider, QueryClient } from "react-query";
const root = ReactDOM.createRoot(document.getElementById("root"));
const queryClient = new QueryClient();
root.render(
);
reportWebVitals();
How To Fetch Data With Tanstack
Now, we are going to fetch some data from an endpoint using Tanstack. We need to import useQuery from react-query (Tanstack).
import { useQuery } from "react-query";
Then we will destructure it and get the isLoading, data and the error states from it. These states will enable us to carryout the optimistic UI updates. This will enable us to conditionally render different UI based on the state of the data.
const id = useParams()
const { isLoading, data, error } = useQuery(["post", id.id], () =>
getSignleQueryFunc(id.id)
)
Then we have to pass a query, a query is a declarative dependency on an asynchronous source of data that is tied to a unique key. This query will help us to fetch data. In our case, we have an array of a string (post) an the id of each post. It doesn`t really matter, just make sure that it is unique.
Here is an example from the Tanstack documentation.
import { useQuery } from 'react-query'
function App() {
const info = useQuery('todos', fetchTodoList)
}
Next, we have to include the query function, this query function enables us to fetch the data from an endpoint. In our case, we created our function in a separate file and imported it. Here is our query function
export async function getSignleQueryFunc(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
return response.json();
}
This is the final result
import { useQuery } from "react-query";
import { getSignleQueryFunc } from "./getSignlePost";
import { useParams } from "react-router-dom";
export default function Posts() {
const id = useParams();
const { isLoading, data, error } = useQuery(["post", id.id], () =>
getSignleQueryFunc(id.id)
);
if (error && data == undefined) return <p>Error fetching post</p>;
return (
<main>
<h1>post</h1>
<div>
{isLoading ? (
<div>Loading...</div>
) : (
<div>
<h3>{data.title}</h3>
<p>{data.body}</p>
<p>the number is {data.id}</p>
</div>
)}
</div>
</main>
);
}
As you can clearly see how easy it is to use Tanstack (react query) to fetch data. You don`t need to use useStates anymore to determine the state of your data. In this example, we fetched single posts.
Mutations
Mutations enables you to create, delete and update data. Tanstack has useMutation which you will use to create, delete and update data.
We have to pass the mutation function to the useMutation, and then supply the function with the necessary parameters for the specific mutation operation you want to perform. In our case, we will be updating the posts.
Here is how it is done
`
import { editPostFunc } from "./editPost";
import { useQuery, useMutation } from "react-query";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { getSignleQueryFunc } from "./getSignlePost";
export default function UpdatePost() {
const id = useParams();
const { data } = useQuery(["post", id.id], () => getSignleQueryFunc(id.id));
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
useEffect(() => {
if (data) {
setTitle(data.title || "");
setBody(data.body || "");
}
}, [data]);
const itemUpdate = useMutation(editPostFunc, {
onSuccess: () => {
console.log("Post updated successfully");
},
onError: (error) => {
console.error("Error updating post:", error);
},
});
const handleSubmit = (e) => {
e.preventDefault();
const updatedData = {
id: id.id,
title: title,
body: body,
userId: data.userId,
};
itemUpdate.mutate(updatedData);
};
return (
hello everyone
type="text"
placeholder="first input"
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
type="text"
placeholder="second input"
name="body"
value={body}
onChange={(e) => setBody(e.target.value)}
/>
click
</main>
);
}`
Here is how our editPostFunc looks like
https://jsonplaceholder.typicode.com/posts/${updatedData.id}`,
export async function editPostFunc(updatedData) {
const res = await fetch(
{
method: "PUT",
body: JSON.stringify({
id: updatedData.id,
title: updatedData.title,
body: updatedData.body,
userId: updatedData.userId,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
}
);
return res.json();
}
`
As you can see, we are fetching each post and storing the values in the useStates so that we can be able to edit them in the input fields. Once we are done editing it, we call the handleSubmit function. In this function, we are creating an object with the necessary property values, this includes the states we updated.
We will then send the object to the mutation function for the update. We also check if the edit was successful or not by console logging the result we are getting whenever we try to update a post.
You can clearly see how easy it is to carryout HTTP requests with Tanstack.
Difference between useQuery and useMutation
Use cases: useQuery is used to fetch data while useMutation is used for modifying data.
Conclusion
HTTP request is a very essential part of modern web development, it allow browsers to initiate a communication with a server to perform some actions like GET, POST, PUT, DELETE, PATCH etc. Tanstack on the other hand helps to make things easier for developers, it has some many benefits like optimistic UI updates, simplified data fetching etc.
I believe you have seen how easy it is to use Tanstack to handle HTTP requests and data management. Check out the Tanstack documentation here for more understanding and to explore other features of Tanstack.
Happy coding!
Top comments (1)
Sorry that some of those codes didn
t appear nicely, I tried to solve that but I couldn
t. Please if you have solution for that, do let me know.