Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactQuery await .mutate

Tags:

react-query

Ok, I'n new to reactQuery and cant wrap my head around this.

useUpdateUserSettings is a import from a custom hook.

I have a page that calls this function:

  const updateUserSettingsMutation = useUpdateUserSettings();

  updateUserSettingsMutation.mutate({
    userName: user.preferred_username,
    settings: {
      ...settings,
      treatmentCountryGuid: country?.id || "",
      legalDepartmentGuid: division?.legalDepartmentGuid || "",
      defaultLanguage: selectedLanguage || "",
      treatmentCountryCode: country?.code || "",
      shopCode: division?.shopName?.substring(0, 2) || "",
    },
  });

Here is the function:

export function useUpdateUserSettings() {
  const queryClient = useQueryClient();
  return useMutation(
    async (vars: { userName: string; settings: IUserSettingsForUpdate }) =>
    await putAccountSettings(vars.userName, vars.settings),
    {
      onMutate: async () => {
        queryClient.cancelQueries(useUserSettings.queryKey);
      },
      onSettled: () => queryClient.invalidateQueries(useUserSettings.queryKey),
    },
  );
}

On the page that calls updateUserSettingsMutation I need to await it to finish before the code continues.

UPDATE: It can be done like this:

updateUserSettingsMutation.mutate({
  userName: user.preferred_username,
  settings: {
    ...settings,
    treatmentCountryGuid: country?.id || "",
    legalDepartmentGuid: division?.legalDepartmentGuid || "",
    defaultLanguage: selectedLanguage || "",
    treatmentCountryCode: country?.code || "",
    shopCode: division?.shopName?.substring(0, 2) || "",
  },
}, { onSuccess: () => { Some code }})
like image 515
ComCool Avatar asked Jul 31 '26 23:07

ComCool


2 Answers

Instead of calling updateUserSettingsMutation.mutate, you would use updateUserSettingsMutation.mutateAsync. This allows you to await the completion of the mutation.

const updateUserSettingsMutation = useUpdateUserSettings()

await updateUserSettingsMutation.mutateAsync({
    userName: user.preferred_username,
    settings: {
        // ... your settings object
    },
})

For more details: https://tanstack.com/query/v4/docs/react/guides/mutations#promises

like image 92
Anik Saha Avatar answered Aug 02 '26 14:08

Anik Saha


updateUserSettingsMutation.mutate({
  userName: user.preferred_username,
  settings: {
    ...settings,
    treatmentCountryGuid: country?.id || "",
    legalDepartmentGuid: division?.legalDepartmentGuid || "",
    defaultLanguage: selectedLanguage || "",
    treatmentCountryCode: country?.code || "",
    shopCode: division?.shopName?.substring(0, 2) || "",
  },
}, { onSuccess: () => { Some code }})
like image 39
ComCool Avatar answered Aug 02 '26 15:08

ComCool