ホームページ  >  記事  >  ウェブフロントエンド  >  TanStack の使用方法 (React Query)

TanStack の使用方法 (React Query)

WBOY
WBOYオリジナル
2024-07-20 08:48:59900ブラウズ

今日の最新の Web 開発では、アプリケーションにとって HTTP リクエストが非常に重要であるため、効率的なデータ管理の必要性がますます重要になっています。この記事では、Tanstack の概要、主な機能、および開始方法について説明します。

タンスタック

Tanstack は、アプリケーションのデータ管理のための素晴らしいライブラリであり、非同期データ操作のデータ管理の問題に対処します。開発者が HTTP リクエストを簡単に実行できるようにします。

HTTP リクエストとは何ですか?

HTTP リクエスト (ハイパーテキスト転送プロトコル) は、通常、通信を開始し、データまたはアクションを要求するためにブラウザーからサーバーに送信されるメッセージです。 HTTP は World Wide Web にとって非常に重要であり、Web の基本的な部分です。それがなければ、アプリケーションが存在しない可能性があります。

HTTP リクエストにより、フロントエンド アプリケーションはエンドポイントを介してサーバー上で GET、POST、PUT、DELETE、PATCH などのアクションを実行できます。

Tanstack を使用する利点

キャッシュとデータ同期: 組み込みのキャッシュ メカニズムを使用して、tanstack はデータをローカルに保存することでアプリケーションのパフォーマンスを最適化します。これによりリクエストの数が減り、アプリケーションが大幅に高速化されます。

楽観的な更新: Tanstack は楽観的な更新を促進し、開発者がそれに応じて UI を更新できるようにします。エラー、isLoading などの驚くべき状態があります。これらを使用すると、データの読み込み中に条件付きで読み込み状態をレンダリングできます。

自動ページネーションと無限ロード: Tanstack の自動ページネーションと無限ロードのサポートにより、大規模なデータセットの処理が容易になります。開発者はデータをチャンク単位でシームレスに取得して表示できるため、アプリケーションのパフォーマンスとユーザー エクスペリエンスが向上します。
タンスタックの使い方

まず、ターミナルで npm i react-query を実行して、tanstack をインストールする必要があります。

Tanstack を使用できるようにするには、アプリケーションに QueryClientProvider を挿入する必要があります。また、QueryClient をプロパティとして提供します。これはアプリケーションのindex.jsファイルで作成できます。


import React from "react";
"react-dom/client" から ReactDOM をインポートします;
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();

Tanstack でデータを取得する方法

ここで、Tanstack を使用してエンドポイントからデータを取得します。 useQuery をreact-query (Tanstack) からインポートする必要があります。

「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 の使用方法 (React Query)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。