๐Ÿ’ซ Better data fetching with SWR (์˜๋ฌธ)

yaytomatoยท2020๋…„ 12์›” 30์ผ
3

React

๋ชฉ๋ก ๋ณด๊ธฐ
3/4
post-thumbnail

SWR is a React hooks library for data fetching built by vercel (maintainer of Next.js). Enables fast, lightweight, reusuable data fetching with built-in caching and request deduplication handling (stops duplicate requests from being sent).

Installation

yarn add swr

or

npm install swr

Handling GET

Basic use

import axios from "axios";
import useSWR from "swr";

const get = (url) => axios.get(url).then((res) => res.data);

const Greetings = () => {
  const { data, error } = useSWR("/api/user/123", get);

  if (error) return <div>error</div>;
  if (!data) return <div>loading...</div>;

  return <div>hello {data.name}!</div>;
};

Creating SWR hooks for reuse

const useUser = (id) => {
  const { data, error } = useSWR(`/api/user/${id}`, get);

  return {
    user: data,
    isLoading: !error && !data,
    isError: error,
  };
};
const Avatar = ({ id }) => {
  const { user, isLoading, isError } = useUser(id);

  if (isLoading) return <Spinner />;
  if (isError) return <Error />;
  return <img src={user.avatar} />;
};

Refetch on interval

import useSWR from "swr";

const Greetings = () => {
  const { data } = useSWR("/api/users", get, {
    refreshInterval: 60 * 60 * 24 * 1000, // refetches data every 24 hours
  });

  return ...
};

Handling POST

import axios from "axios";
import useSWR, { mutate } from "swr";

const updateUser = (user) =>
  axios.post("/api/user", user).then((res) => res.data);

const Greetings = () => {
  const { data } = useSWR("/api/user", get);

  const uppercase = () => {
    const newUser = { ...data, name: data.name.toUpperCase() };
    mutate("/api/user", newUser, false); // mutate local state without revalidation
    mutate("/api/user", updateUser(newUser));
  };

  return (
    <div>
      <h1>Hi {data.name}</h1>
      <button onClick={}>Uppercase</button>
    </div>
  );
};
profile
2021 ๋ชฉํ‘œ: ๋ฏฟ์Œ๊ณผ ์ดํƒ€์‹ฌ์œผ๋กœ ๊ฝ‰์ฐฌ ํ•œ ํ•ด ๋˜๊ธฐ

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

comment-user-thumbnail
2020๋…„ 12์›” 31์ผ

SWR์„ ์• ์šฉํ•ด์™”์—ˆ๋Š”๋ฐ react-query๋ฅผ ์“ฐ๋‹ค๋ณด๋‹ˆ react-query๊ฐ€ ์žฅ์ ์ด ํ›จ์”ฌ ๋ˆˆ์— ๋” ๋งŽ์ด ๋“ค์–ด์˜ค๋”๋ผ๊ตฌ์š”.
๊ทธ๋ž˜๋„ ์˜๊ฒฌ์ด ๋งŽ์ด๋“ค ๊ฐˆ๋ ค์„œ react-query vs SWR ์–ด๋–ป๊ฒŒ ๋ณด์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.

1๊ฐœ์˜ ๋‹ต๊ธ€
comment-user-thumbnail
2021๋…„ 3์›” 24์ผ

์ตœ๊ณ ๋„ค์š”!๐Ÿ‘๐Ÿ€

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ