首頁 > 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學習者快速成長!