๐Ÿ“† 22.11.02 - react query

๋ฒ„๋“คยท2022๋…„ 11์›” 2์ผ
0

โœจToday I Learn (TIL)

๋ชฉ๋ก ๋ณด๊ธฐ
13/62
post-thumbnail
post-custom-banner

react query ์˜ ์žฅ์ 

  • Caching
  • get์œผ๋กœ ๋ฐ›์•„์˜จ ๋ฐ์ดํ„ฐ๋ฅผ update์„ ํ•˜๋ฉด ์ž๋™์œผ๋กœ get์„ ๋‹ค์‹œ ์ˆ˜ํ–‰
  • ๋ฐ์ดํ„ฐ๊ฐ€ ์˜ค๋ž˜๋˜์—ˆ๋‹ค ํŒ๋‹จ๋˜๋ฉด invalidateQueries๋ผ๋Š” get์š”์ฒญ์„ ํ•จ
  • ๋ฌดํ•œ์Šคํฌ๋กค (Infinite Queries)
  • reack hook๊ณผ ๋งŽ์ด ํก์‚ฌํ•จ

์„ค์น˜๋Š” npm install react-query

๊ทธ๋ฆฌ๊ณ  root๋‹จ์— index.js ์—์„œ ๊ธฐ๋ณธ์ž‘์—…์„ ์ง„ํ–‰ํ•ด์ค€๋‹ค.

// index.js ์ค‘๋žต
import { QueryClient, QueryClientProvider } from "react-query"
import {ReactQueryDevtools} from "react-query/devtools"


const queryClient = new QueryClient();

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      {/* devtools */}
      <ReactQueryDevtools initialIsOpen={true} />
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

useQuery

get์„ ์œ„ํ•œ react query api์ด๋‹ค. ์˜ค์ง get๋งŒ์ด๋ฉฐ post, update๋Š” useMutation์„ ์‚ฌ์šฉ

์ฒซ๋ฒˆ์งธ parameter๋กœ unique key๊ฐ€ ๋“ค์–ด๊ฐ€๊ณ  ๋‘๋ฒˆ์งธ๋Š” ๋น„๋™๊ธฐ ํ•จ์ˆ˜, ์ฆ‰ api ํ˜ธ์ถœ์ด ๋“ค์–ด๊ฐ„๋‹ค.

  • useQuery ๋Š” ๋น„๋™๊ธฐ๋กœ ์ž‘๋™ํ•˜๊ธฐ์— (async await ์—ฌ๋ถ€์™€ ๊ด€๊ณ„์—†์ด) ํ•œ ๊ฐœ์˜ useQuery์—์„œ๋Š” ํ•˜๋‚˜์˜ api ํ˜ธ์ถœ๋งŒ ์ด๋ฃจ์–ด์ ธ์•ผ๋œ๋‹ค. ๋‘ ๊ฐœ ์ด์ƒ์€ useQueries์—์„œ

์˜ˆ์‹œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ์ถœ์ฒ˜๋Š” https://kyounghwan01.github.io/blog/React/react-query/basic/#usequery

const Todos = () => {
  const { isLoading, isError, data, error } = useQuery("todos", fetchTodoList, {
    refetchOnWindowFocus: false, // react-query๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์‚ฌ์šฉํ•˜๋Š” ์œˆ๋„์šฐ๊ฐ€ ๋‹ค๋ฅธ ๊ณณ์„ ๊ฐ”๋‹ค๊ฐ€ ๋‹ค์‹œ ํ™”๋ฉด์œผ๋กœ ๋Œ์•„์˜ค๋ฉด ์ด ํ•จ์ˆ˜๋ฅผ ์žฌ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ ์žฌ์‹คํ–‰ ์—ฌ๋ถ€ ์˜ต์…˜ ์ž…๋‹ˆ๋‹ค.
    retry: 0, // ์‹คํŒจ์‹œ ์žฌํ˜ธ์ถœ ๋ช‡๋ฒˆ ํ• ์ง€
    onSuccess: data => {
      // ์„ฑ๊ณต์‹œ ํ˜ธ์ถœ
      console.log(data);
    },
    onError: e => {
      // ์‹คํŒจ์‹œ ํ˜ธ์ถœ (401, 404 ๊ฐ™์€ error๊ฐ€ ์•„๋‹ˆ๋ผ ์ •๋ง api ํ˜ธ์ถœ์ด ์‹คํŒจํ•œ ๊ฒฝ์šฐ๋งŒ ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค.)
      // ๊ฐ•์ œ๋กœ ์—๋Ÿฌ ๋ฐœ์ƒ์‹œํ‚ค๋ ค๋ฉด api๋‹จ์—์„œ throw Error ๋‚ ๋ฆฝ๋‹ˆ๋‹ค. (์ฐธ์กฐ: https://react-query.tanstack.com/guides/query-functions#usage-with-fetch-and-other-clients-that-do-not-throw-by-default)
      console.log(e.message);
    }
  });

  if (isLoading) {
    return <span>Loading...</span>;
  }

  if (isError) {
    return <span>Error: {error.message}</span>;
  }

  return (
    <ul>
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
};
profile
ํƒœ์–ด๋‚œ ๊น€์— ๋งŽ์€ ๊ฒฝํ—˜์„ ํ•˜๋ ค๊ณ  ์•„๋“ฑ๋ฐ”๋“ฑ ์• ์“ฐ๋Š” ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€