next.jsreact-querytrpc

Unable to Retrieve Data from useMutation Call Despite Successful Internal Fetch


I'm relatively new to tRPC so please bear with me on this. I'm encountering an issue with the useMutation query. When I call useMutation with new input, it returns undefined for data. However, I can see that the data is successfully retrieved internally, as confirmed by tRPC's debugging console and an onSuccess call within the useMutation variable.

I'm struggling to understand how to properly rretrieve mutated data with tRPC, and I would appreciate some guidance on resolving this issue.

Front-End

  // fetch data
  const dataMutation = api.post.queryByFilter.useMutation({
    onSuccess(data) {
      console.log("onSuccess: ", data);
    },
  });

  const fetchData = async () => {
    // set dates for query
    setMonthsBack(monthsBack + 1);
    const currentDate = new Date();
    currentDate.setMonth(currentDate.getMonth() - monthsBack);
    const getMonth = (currentDate.getMonth() + 1).toString();
    const getYear = currentDate.getFullYear().toString();

    dataMutation.mutate({
      company: "google",
      month: getMonth.toString(),
      year: getYear,
    });

    console.log("Fetch Data: ", dataMutation.data);

    // append to cardSets; not relevant for this example
    setCardSets([
      ...cardSets,
      { data: dataMutation, month: getMonth.toString(), year: getYear },
    ]);
    // increment page; not relevant for this example
    setPage(page + 1);
  };

Back-End

  queryByFilter: publicProcedure
    .input(
      z.object({
        company: z.string(),
        month: z.string(),
        year: z.string(),
      }),
    )
    .mutation(({ input, ctx }) => {
      const { company, month, year } = input;

      const startDate = new Date(`${year}-${month}-01`);
      const endDate = new Date(`${year}-${month}-31`);

      return ctx.db.spottings.findMany({
        where: {
          company: company,
          date: { gte: startDate, lte: endDate },
        },
        orderBy: { date: "desc" },
      });
    }),

Solution

  • dataMutation.mutate is any async operation. It calls your backend and successfully resolves the API call with data, but if you try to access the .data immediately, it's not there yet. That's why there is an onSuccess callback.

    You can either use the onSuccess like so:

        dataMutation.mutate({
          company: "google",
          month: getMonth.toString(),
          year: getYear,
        }, {
          onSuccess: (data) => {
            console.log("Fetch Data: ", data);
            // put your code here
          }
        });
    

    or you should be able to leverage mutateAsync API:

        const data = await dataMutation.mutateAsync({
          company: "google",
          month: getMonth.toString(),
          year: getYear,
        }
        console.log("Fetch Data: ", data);
        // put your code here
    

    see official docs https://tanstack.com/query/v4/docs/framework/react/guides/mutations