React Query refetch multiple keys

Daftar Isi

Perkenalan

Hello Word! kali ini penulis akan menbahas menggenai react query, jadi tuh hari ini penulis mendapatkan masalah untuk melakukan fetch ulang dengan mengunakan react query tapi hanya beberapa keys saja yang akan di fetch ulang.

Masalah

Masalah nya adalah react query client hanya dapat melakukan fetch ulang hanya dengan satu key saja dengan mengunakan Custom Hooks sebagai contoh:
				
					import { useQueryClient } from 'react-query'

function MyComponent() {
  const queryClient = useQueryClient()

  const handleRefetch = async () => {
    await queryClient.refetchQueries('myQueryKey')
  }

  return (
    <div>
      <button onClick={handleRefetch}>Refetch</button>
    </div>
  )
}

				
			

pada baris ke 7 menunjukan kalau hanya bisa mengunakan satu ke saja untuk melakukan fetch ulang ke backend.

Diselesaikan

Lantas bagaimana cara nya untuk melakukan refetch dengan keys yang banyak. Rupanya cara untuk handle fetching ulang dengan key yang banyak tidak lah susah. 

				
					import React, { useEffect, useState } from "react";
import { useQueryClient } from 'react-query'

function MyComponent() {
  const queryClient = useQueryClient();
  const [queryKeysList, setQueryKeysList] = useState([]);

  const handleRefetch = async () => {
    queryKeysList.forEach( async (itemKey) => {
         await queryClient.refetchQueries(itemKey);
    }
  }
  
  useEffect(() => {
    const queryCache = queryClient.getQueryCache();
		const queryKeys = queryCache.getAll().map(cache => cache.queryKey);
		const stringKeysQuery: string[] = [];

		queryKeys.forEach(item => {
			stringKeysQuery.push(item as unknown as string);
			}
		});
		
		setQueryKeysList(stringKeysQuery);
  },[])

  return (
    <div>
      <button onClick={handleRefetch}>Refetch</button>
    </div>
  )
}

				
			

Pada Source Code kali ini pada line 15 dan 16 mengambil data keys yang ada di cache react query, kemudian pada line 19 keseluruhan key tersebut akan di masukan ke state queryKeysList. Kemudian untuk handleRefetch nya akan di lakukan perulangan untuk setiap key nya supaya setiap key akan di lakukan fecthing ulang ke backend.

Facebook
Twitter
LinkedIn
WhatsApp
Telegram
Dwiki Nuri Dhuha
Dwiki Nuri Dhuha
Hello World! Let me introduce myself, I’m Dwiki Nuri Dhuha from Indonesia & i’m Computer Geek – Full Stack – Engineer – Introvert – Perfectionist – Workaholic.

Leave a Reply

Your email address will not be published. Required fields are marked *