0

I am checking out trpc with t3 stack and I want to update a state when useQuery is successful.

and I am getting typescript error on the frontend,

Argument of type '{ onSuccess: (shoppingList: ShoppingItem[]) => void; }' is not assignable to >parameter of type 'void'.

I am doing something like this on my frontend,

const [items, setItems] = useState<ShoppingItem[]>([]);
  const { data: itemsData, isLoading } = trpc.item.getItem.useQuery({
    onSuccess: (shoppingList) => {
      setItems(shoppingList);
    },
  });

this is my backend route,

getItem: publicProcedure.query(async ({ ctx }) => {
    const items = await ctx.prisma.shoppingItem.findMany();
    return items;
  })

3 Answers3

2

I guesse it can be a solution

 const [items, setItems] = useState<ShoppingItem[]>([]);   const {
 data: itemsData, isLoading } = trpc.item.getItem.useQuery(undefined ,
 { onSuccess: (shoppingList) => {setItems(shoppingList)} 
 });
chub
  • 21
  • 3
0

I believe you are missing a parameter in your useQuery, you need to pass an array as your first parameter which will be the query key. So it could look something like this -

const [items, setItems] = useState<ShoppingItem[]>([]);
  const { data: itemsData, isLoading } = trpc.item.getItem.useQuery(['some-key'], {
    onSuccess: (shoppingList) => {
      setItems(shoppingList);
    },
  });
0

In React Query v4 onSuccess is depricated. (as stated in @tanstack/react-query documentation)

The best thing to do now is to use useEffect where the data is a dependency.

useEffect(()=>{
  setItems(itemsData)
}, [itemsData]);
Davo
  • 526
  • 3
  • 19
  • I understand this is not the solution to your problem per se, but it is important to know not to use `onSuccess`, `onError` since they will not be available in future versions. – Davo Jun 05 '23 at 13:51