1

I think Wagmi uses react-query under the hood. So I want to refresh queries whenever and wherever I wanted using invalidateQueries method like we use to do with react-query.

Here is the query that I want to refetch:

  import { useContractRead } from 'wagmi';

  const balance = useContractRead({
    address: --random-adress--,
    abi: random.abi,
    functionName: 'balanceOf',
    onSuccess: () => {
      console.log('balanceOf refeched');
    },
    cacheTime: 0,
    staleTime: 0,
    scopeKey: 'balanceOf',
  });

And here is the implementation of invalidation:


import { useQueryClient } from 'wagmi';

function App() {
  const queryClient = useQueryClient();

  return (
    <button
      onClick={() => {
        queryClient.invalidateQueries({ queryKey: ['balanceOf'] });
      }}
    >
      Click Me!
    </button>
  );
}

export default App;

First I thought the function name is also query key but it's not worked. Then I added scopeKey hoping it would be the queryKey but it still not works.

Version: wagmi@1.^*

Nightvision
  • 96
  • 12

1 Answers1

0

One way is to use refetch from useContractRead returned value. you can create a custom hook named useGetBalance and then use It all over the place.

useGetBalance hook :

export const useGetBalance = ()=>{
return useContractRead({
address: --random-adress--,
abi: random.abi,
functionName: 'balanceOf',
onSuccess: () => {
  console.log('balanceOf refeched');
},
cacheTime: 0,
staleTime: 0,
scopeKey: 'balanceOf',
});

usage :

function App() {
const {refetch:refetchBalance} = useGetBalance();

 return (
 <button
  onClick={() => {
    refetchBalance?.()
  }}
>
  Refetch !
</button>
);
}

export default App;
Sepanta
  • 91
  • 5
  • Let's say I use this on my header component to show my balance. If I wanted to update this balance after I make a transaction or something on a diffrent component, I need to pass that refetch function all the way trough that component. The 'invalidateQueries' api is much clean way to done this. – Nightvision Jun 27 '23 at 15:19
  • 1
    @Nightvision I think this also might be an option : https://wagmi.sh/react/hooks/useContractRead#watch-optional – Sepanta Jun 27 '23 at 18:41