首页 > web前端 > js教程 > 正文

如何使用 TanStack(反应查询)

WBOY
发布: 2024-07-20 08:48:59
原创
899 人浏览过

在当今的现代 Web 开发中,HTTP 请求对于应用程序至关重要,因此高效数据管理的需求变得越来越重要。本文将向您介绍 Tanstack、它的主要功能以及如何开始使用。

Tanstack

Tanstack 是一个令人惊叹的应用程序数据管理库,它解决了异步数据操作的数据管理问题。它可以帮助开发者轻松地进行HTTP请求。

什么是 HTTP 请求?

HTTP 请求(超文本传输​​协议)通常是浏览器向服务器发送的消息,用于发起通信并请求数据或操作。 HTTP 对于万维网非常重要,它是网络的基本组成部分。没有它,我们可能就没有应用程序。

HTTP 请求允许前端应用程序通过端点在服务器上执行 GET、POST、PUT、DELETE、PATCH 等操作。

使用 Tanstack 的好处

缓存和数据同步:借助内置的缓存机制,tanstack 通过在本地存储数据来优化应用程序的性能。这减少了请求数量,从而使您的应用程序速度更快。

乐观更新:Tanstack 促进乐观更新,这使开发人员能够相应地更新 UI。它有令人惊奇的状态,例如错误、isLoading。您可以使用它们在数据加载时有条件地渲染加载状态。

自动分页和无限加载:借助 tanstack 对自动分页和无限加载的支持,处理大型数据集变得毫不费力。开发人员可以无缝地分块获取和显示数据,从而增强应用程序性能和用户体验。
如何使用 Tanstack

首先,我们必须通过在终端上运行 npm i react-query 来安装 tanstack。

我们必须在应用程序中注入 QueryClientProvider,以便我们能够使用 Tanstack。我们还将为其提供 queryClient 作为道具。您可以在应用程序的 index.js 文件中创建它。


从“react”导入React;
从“react-dom/client”导入 ReactDOM;
导入“./index.css”;
从“./App”导入应用程序;
从“./reportWebVitals”导入reportWebVitals;
从“./Nav”导入导航;
从“react-router-dom”导入 { BrowserRouter };
从“react-query”导入 { QueryClientProvider, QueryClient };

const root = ReactDOM.createRoot(document.getElementById("root"));
const queryClient = new QueryClient();
root.render(








);

reportWebVitals();

如何使用 Tanstack 获取数据

现在,我们将使用 Tanstack 从端点获取一些数据。我们需要从react-query(Tanstack)导入useQuery。

从“react-query”导入{ useQuery };

然后我们将对其进行解构并从中获取 isLoading、数据和错误状态。这些状态将使我们能够进行乐观的 UI 更新。这将使我们能够根据数据的状态有条件地渲染不同的 UI。


const id = useParams()
const { isLoading, data, error } = useQuery(["post", id.id], () =>
getSignleQueryFunc(id.id)
)

然后我们必须传递一个查询,查询是对绑定到唯一键的异步数据源的声明性依赖。这个查询将帮助我们获取数据。在我们的例子中,我们有一个字符串(帖子)数组和每个帖子的 id。这并不重要,只要确保它是唯一的即可。

这是来自 Tanstack 文档的示例。

import { useQuery } from 'react-query'

function App() {
  const info = useQuery('todos', fetchTodoList)
}
登录后复制

接下来,我们必须包含查询函数,该查询函数使我们能够从端点获取数据。在我们的例子中,我们在一个单独的文件中创建了函数并导入它。这是我们的查询函数

export async function getSignleQueryFunc(id) {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${id}`
  );
  return response.json();
}
登录后复制

这是最终结果

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>
  );
}
登录后复制

您可以清楚地看到使用 Tanstack(反应查询)获取数据是多么容易。您不再需要使用 useStates 来确定数据的状态。在此示例中,我们获取了单个帖子。

React query

突变

突变使您能够创建、删除和更新数据。 Tanstack 有 useMutation,您将用它来创建、删除和更新数据。

我们必须将变异函数传递给 useMutation,然后为该函数提供您要执行的特定变异操作所需的参数。就我们而言,我们将更新帖子。

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>
登录后复制

);
}`

How To Use TanStack (React Query)

Here is how our editPostFunc looks like


export async function editPostFunc(updatedData) {
const res = await fetch(
https://jsonplaceholder.typicode.com/posts/${updatedData.id}`,
{
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!

以上是如何使用 TanStack(反应查询)的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!