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

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

React

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

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 ๋ชฉํ‘œ: ๋ฏฟ์Œ๊ณผ ์ดํƒ€์‹ฌ์œผ๋กœ ๊ฝ‰์ฐฌ ํ•œ ํ•ด ๋˜๊ธฐ
post-custom-banner

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

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

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

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

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

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ
comment-user-thumbnail
2021๋…„ 4์›” 20์ผ

ํ•ญ์ƒ ์œ ์ตํ•œ ๊ธ€ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค ์ž˜ ๋ณด๊ณ  ์žˆ์–ด์š” : )

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ
comment-user-thumbnail
2021๋…„ 4์›” 20์ผ

์ข‹์•„์š” :D

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