React-query / Handling Error

๋ฐ•๋‹ค์˜ยท2023๋…„ 1์›” 5์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
24/28

๐Ÿ”— Handling Error ๊ธฐ๋ณธ pattern


๋‚˜๋จธ์ง€ ๋ถ€๋ถ„์€ React-query / Fetching Data ์™€ ๋™์ผํ•˜๋‹ค.

1. results ๋ฅผ destructuring ํ•ด์„œ isError ์™€ error ๋ฅผ ์ถ”๊ฐ€๋กœ ๊บผ๋‚ด์ค€๋‹ค.

result => { isLoading, data, isError, error }

import { useQuery } from 'react-query';

2. ๋ถˆ๋Ÿฌ์˜จ ๊ฐ’์„ ํ™œ์šฉํ•ด์„œ jsx ๋ Œ๋”๋ง ํ•˜๊ธฐ

์ƒํƒœ๊ฐ’์ด ์—๋Ÿฌ๋ฉด ์•„๋ž˜์˜ ์—๋Ÿฌ๋ฉ”์„ธ์ง€๋ฅผ ๊ฐ€์ ธ์™€์„œ ๋ณด์—ฌ์ฃผ๊ธฐ
Request failed with status code 404

if (isError) {
  return <h2>{error.message}</h2>;
}

๐Ÿ“„ code example

import { useQuery } from 'react-query'; // import data fetching Hook
import axios from 'axios';

export const RQSuperHeroesPage = () => {
  // Hook ๋ถˆ๋Ÿฌ์˜ค๊ธฐ // 1. (unique key) ์™€ 2. (promise ๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜)๋ฅผ ์ธ์ž๋กœ ๋ฐ›๋Š”๋‹ค.
  // ex) ํ•จ์ˆ˜๋Š” json server ๋กœ๋ถ€ํ„ฐ get request ๋ฅผ ํ•œ๋‹ค.
  // query hook ์„ ํ†ตํ•ด์„œ ๋ฆฌํ„ด๋œ query result ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
  // results ๋Š” ํ˜„์žฌ query ์—์„œ ๋‚ด๊ฐ€ ํ•„์š”๋กœํ•œ ๋ชจ๋“  ๊ฒƒ์ด ๋‹ด๊ฒจ์žˆ๋‹ค.
  // results ์•ˆ์—์„œ ๋‚ด๊ฐ€ ํ•„์š”ํ•œ ์š”์†Œ๋งŒ destructuring ํ•œ๋‹ค. result => { isError, ..}
  // useQuery ์˜ ๋‘๋ฒˆ์งธ ์ธ์ž์— inline ์œผ๋กœ data fetching ํ•จ์ˆ˜๋ฅผ ๋„ฃ์ง€ ์•Š๊ณ 
  // ๋ฐ–์—์„œ ์„ ์–ธํ•˜๋Š” ๊ฒƒ(fetchSuperHeroes)์ด react query ์˜ ์ผ๋ฐ˜์ ์ธ pattern
  const fetchSuperHeroes = () => {
    return axios.get('http://localhost:5000/superheroes1');
  };

  const { isLoading, data, isError, error } = useQuery(
    'super-heroes',
    fetchSuperHeroes
  );

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

  // ๋ถˆ๋Ÿฌ์˜จ ๊ฐ’์„ ํ™œ์šฉํ•ด์„œ jsx ๋ Œ๋”๋ง ํ•˜๊ธฐ
  if (isError) {
    return <h2>{error.message}</h2>;
  }

  return (
    <>
      <h2>React Query Super Heroes Page</h2>
      {data?.data.map((hero) => {
        return <div key={hero.name}>{hero.name}</div>;
      })}
    </>
  );
};

React Query Tutorial ์ฐธ๊ณ ํ•˜๋ฉฐ ๊ณต๋ถ€ํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

profile
๊ฐœ๋ฐœ๊ณผ ๋””์ž์ธ ๋‘๋งˆ๋ฆฌ ํ† ๋ผ๋ฅผ!

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

comment-user-thumbnail
2023๋…„ 1์›” 6์ผ

ํ˜น์‹œ ๋ฆฌ์•กํŠธ ์ฟผ๋ฆฌ ๊ณผ์™ธ ๋ฌธ์˜ํ•˜๋ ค๋ฉด ์–ด๋””๋กœ ํ•ด์•ผํ•˜๋‚˜์š”..?

1๊ฐœ์˜ ๋‹ต๊ธ€