react query

Hyun·2022년 8월 13일
0

리액트 쿼리

목록 보기
1/3

App.js

import "./App.css";
import { QueryClient, QueryClientProvider } from "react-query";

import Setting from "./components/Setting.js";
import Profile from "./components/Profile";

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div className="App">
        <Setting />
        <Profile />
      </div>
    </QueryClientProvider>
  );
}

export default App;

exam_one/Setting.js

import { useState } from "react";
import { useQueryClient } from "react-query";

function Setting() {
  const [username, setUsername] = useState("");
  //쿼리 사용설정
  const queryClient = useQueryClient();

  //'username' 이란 key 값의 저장공간에 username 값을 저장한다.
  const handleClick = () => queryClient.setQueriesData("username", username);

  return (
    <div>
      <input value={username} onChange={(e) => setUsername(e.target.value)} />
      <button onClick={handleClick}>update</button>
    </div>
  );
}
export default Setting;

exam_one/Profile.js

import { useQuery } from "react-query";

function Profile(){
    //'username' 이란 key 값을 가진 쿼리데이터를 사용한다. 초기값 지정가능.
    const {data: username} = useQuery('username', { initialData: '', staleTime: Infinity});
    
    return <h1>{username}</h1>
}

export default Profile;

실행 화면

커스텀 훅 사용(재사용성 증가)

exam_one/Hooks.js

import { useQuery, useQueryClient } from "react-query";

//커스텀 훅

//해당 key 값의 쿼리데이터를  저장할 수 있는 커스텀 훅
export const useSetClientState = (key) => {
  const queryClient = useQueryClient();
  return (state) => queryClient.setQueryData(key, state);
};

//해당 key 값의 쿼리데이터를 사용할 수 있는 커스텀 훅
export const useClientValue = (key, initialData) => 
  useQuery(key, {
    initialData,
    staleTime: Infinity,
  }).data;

exam_two/Async

import { QueryClient, QueryClientProvider, useQuery } from "react-query";

function Async() {
  const { isLoading, error, data } = useQuery("repoData", () =>
    fetch("https://api.github.com/repos/tannerlinsley/react-query").then(
      (res) => res.json()
    )
  );

  if (isLoading) return "Loading";
  if (error) return "An error has occured: " + error.message;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{" "}
      <strong>{data.stargazers_count}</strong>{" "}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  );
}

export default Async;

실행 화면

profile
better than yesterday

0개의 댓글