[ReactNative] ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค React Query์˜ useQuery๋กœ ๋‹ค๋ฅธ API ๋ถˆ๋Ÿฌ์˜ค๊ธฐ
728x90

Today, What I learned?

ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉฐ ์นดํ…Œ๊ณ ๋ฆฌ์— ๋”ฐ๋ผ์„œ React Query์˜ useQuery๋ฅผ ํ†ตํ•ด ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ถ€๋ถ„์„ ์ง„ํ–‰ํ•˜๋ฉฐ

์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ๊ฒฐ๊ณผ๋ฌผ์„ ๋งŒ๋“ค์—ˆ๋Š”์ง€ ๊ธฐ๋กํ•ด ๋ณธ๋‹ค.

 

 

ํ”ผ๊ทธ๋งˆ ์ƒ์œผ๋กœ ๋งŒ๋“ค์–ด์•ผ ํ–ˆ๋˜ ๋ถ€๋ถ„์ด๋‹ค.

๊ฐ ์ง€์—ญ์„ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ์ง€์—ญ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์™€์•ผ ํ•˜๋Š” ๋ถ€๋ถ„!

 

 

์ผ๋‹จ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค ๊ฐ ์ง€์—ญ์˜ ์ฝ”๋“œ๋ฅผ API์˜ params ๊ฐ’์œผ๋กœ ๋„˜๊ฒจ์ฃผ์–ด์•ผ ํ–ˆ๋‹ค.

๊ทธ๋ž˜์„œ API ํ•จ์ˆ˜์—์„œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ params๋ฅผ ๋ฐ›์•„์˜ค๊ธฐ๋กœ ํ–ˆ๋‹ค.

export const getLocalPopular = (params) => {
  const [_, category] = params.queryKey;
  return fetch(
    `${BASE_URL}/boxoffice?service=${API_KEY}&ststype=month&date=${getDateString()}&catecode=GGGA&area=${
      category ?? 11
    }`
  )
    ...
};

 

 

refetch ์‚ฌ์šฉํ•ด ๋ณด๊ธฐ?

์ฒ˜์Œ์—๋Š” ์ง€์—ญ ๋ฒ„ํŠผ๋งˆ๋‹ค useQuery์˜ refetch๋ฅผ ์‹คํ–‰ํ•˜๊ฒŒ ํ•˜๋ฉด ์–ด๋–จ๊นŒ? ์‹ถ์—ˆ๋Š”๋ฐ ๋ง ๊ทธ๋Œ€๋กœ ํŒจ์น˜๋ฅผ ๋‹ค์‹œ ํ•ด์˜ค๋Š” ๊ฒƒ์ด์—ˆ๊ณ ..
params๋ฅผ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์—†์—ˆ๋‹ค ใ…Žใ…Ž..

const { data, refetch } = useQuery(['Local'], getLocalPopular);

๊ทธ๋ฆฌ๊ณ  ํด๋ฆญํ•˜์ง€๋„ ์•Š์•˜๋Š”๋ฐ ๊ณ„์† ์ฝ˜์†”์ด ์ฐํžˆ๋Š” ๊ฒƒ์„ ๋ณด๊ณ  ์ด๊ฑด ์•„๋‹Œ ๋ฐฉ๋ฒ•์ด๋ผ๋Š” ๊ฒƒ์„ ๊นจ๋‹ซ๊ณ ..

 

 

 

์ตœ์ข…์ ์œผ๋กœ ์•„๋ž˜์˜ ๊ธ€์„ ์ฐธ๊ณ ํ•ด์„œ ์™„์„ฑํ•œ ์ฝ”๋“œ๋Š” ์ด๋ ‡๋‹ค.

https://stackoverflow.com/questions/67796103/refetch-with-different-data-react-query

 

refetch with different data react query

I try to Refetch every button is click and get a new data const {refetch,data,isLoading} = useQuery( "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? q=${sel...

stackoverflow.com

 

 

 

์™„์„ฑ ์ฝ”๋“œ

useState๋ฅผ ์ด์šฉํ•ด์„œ ์ €์žฅํ•œ ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๊ฐ’์„ useQuery์˜ params๋กœ ๋„˜๊ฒจ์ค€๋‹ค.

const [category, setCategory] = useState(11);
  const { data, isLoading } = useQuery(['Local', category], getLocalPopular);

๋ฒ„ํŠผ ์˜์—ญ์— state ๋ถ€๋ถ„์„ props๋กœ ๋„˜๊ฒจ์ฃผ์–ด, ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ setCategory() ํ•จ์ˆ˜์— ์ฝ”๋“œ๊ฐ’์„ ๋‹ค์‹œ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ–ˆ๋‹ค.

 

  const handleLocalButton = (code) => {
    setCategory(code);
  };
  ...

 {localKeys?.map((local) => (
        <LocalButton
         ...
          onPress={() => handleLocalButton(local?.code)}
        >
         ...
        </LocalButton>
))}

๊ทธ๋Ÿผ category ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค useQuery์˜ ์ฟผ๋ฆฌํ•จ์ˆ˜๊ฐ€ ์žฌ์‹คํ–‰๋œ๋‹ค!

 

๋…นํ™”๊ฐ€ ์ž˜๋ชป๋œ ๊ฒƒ ๊ฐ™์ง€๋งŒ ์ž˜ ์‹คํ–‰๋œ๋‹ค. ๐Ÿ™Œ

useQuery๋กœ params ๋„˜๊ฒจ์ฃผ๋Š” ๋ฐฉ๋ฒ•์„ ์ œ๋Œ€๋กœ ์จ๋ดค์œผ๋‹ˆ ๋‹ค์Œ์—๋„ ์ž˜ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ!..

728x90