>  기사  >  웹 프론트엔드  >  TanStack 사용 방법(반응 쿼리)

TanStack 사용 방법(반응 쿼리)

WBOY
WBOY원래의
2024-07-20 08:48:59900검색

오늘날 현대 웹 개발에서 HTTP 요청은 애플리케이션에 매우 중요하므로 효율적인 데이터 관리의 필요성이 점점 더 중요해지고 있습니다. 이 기사에서는 Tanstack의 주요 기능과 시작 방법을 소개합니다.

탄스택

Tanstack은 애플리케이션의 데이터 관리를 위한 놀라운 라이브러리로, 비동기 데이터 작업에 대한 데이터 관리 문제를 해결합니다. 개발자가 HTTP 요청을 쉽게 수행할 수 있도록 도와줍니다.

HTTP 요청이란 무엇인가요?

HTTP 요청(Hypertext Transfer Protocol)은 일반적으로 통신을 시작하고 데이터나 작업을 요청하기 위해 브라우저에서 서버로 보내는 메시지입니다. HTTP는 World Wide Web에 매우 중요하며 웹의 기본 부분입니다. 이것이 없으면 애플리케이션이 없을 수도 있습니다.

HTTP 요청을 사용하면 프런트엔드 애플리케이션이 엔드포인트를 통해 서버에서 GET, POST, PUT, DELETE, PATCH 등의 작업을 수행할 수 있습니다.

Tanstack 사용의 장점

캐싱 및 데이터 동기화: 내장된 캐싱 메커니즘을 통해 tanstack은 데이터를 로컬에 저장하여 애플리케이션 성능을 최적화합니다. 이렇게 하면 요청 수가 줄어들어 애플리케이션 속도가 훨씬 빨라집니다.

낙관적 업데이트: Tanstack은 낙관적 업데이트를 촉진하므로 개발자가 이에 따라 UI를 업데이트할 수 있습니다. isLoading 오류와 같은 놀라운 상태가 있습니다. 이를 사용하여 데이터가 로드되는 동안 조건부로 로드 상태를 렌더링할 수 있습니다.

자동 페이지 매김 및 무한 로딩: tanstack의 자동 페이지 매김 및 무한 로딩 지원으로 대규모 데이터 세트를 쉽게 처리할 수 있습니다. 개발자는 데이터를 청크로 원활하게 가져오고 표시하여 애플리케이션 성능과 사용자 경험을 향상시킬 수 있습니다.
탄스택 사용법

먼저 터미널에서 npm i React-query를 실행하여 tanstack을 설치해야 합니다.

Tanstack을 사용할 수 있으려면 애플리케이션에 QueryClientProvider를 삽입해야 합니다. 또한 이를 prop으로 queryClient와 함께 제공할 것입니다. 애플리케이션의 index.js 파일에서 이를 생성할 수 있습니다.


"react"에서 React를 가져옵니다.
"react-dom/client"에서 ReactDOM을 가져옵니다.
import "./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();
루트.렌더(








);

reportWebVitals();

Tanstack으로 데이터를 가져오는 방법

이제 Tanstack을 사용하여 엔드포인트에서 일부 데이터를 가져오겠습니다. 반응 쿼리(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

돌연변이

Mutation을 사용하면 데이터를 생성, 삭제, 업데이트할 수 있습니다. Tanstack에는 데이터를 생성, 삭제 및 업데이트하는 데 사용할 useMutation이 있습니다.

useMutation에 mutation 함수를 전달한 다음 수행하려는 특정 mutation 작업에 필요한 매개변수를 함수에 제공해야 합니다. 저희의 경우 게시물을 업데이트할 예정입니다.

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.