UniQue
UniQue

Reputation: 43

how to update group array when i create new group using ReactQuery useMutation

I want to create a group and update my group list immediately but here I have to refresh the page and get fresh data

fetch and create custom hooks create group function in component level

Upvotes: 0

Views: 55

Answers (1)

TkDodo
TkDodo

Reputation: 28938

Your code looks good, but you probably want an optimistic update: Update the groups locally before the request happens, and then potentially rollback when an error occurs. This is covered in the docs here. In your case, something like:

useMutation(
  values => createGroup(values),
  {
    onMutate: async value => {
      await queryClient.cancelQueries('groups')
 
      const previousGroups = queryClient.getQueryData('groups')
 
      queryClient.setQueryData('groups', old => [...old, value])
 
      return { previousGroups }
    },
    onError: (err, values, context) => {
      queryClient.setQueryData('groups', context.previousGroups)
    },
    onSettled: () => {
      queryClient.invalidateQueries('groups')
    }
  }
)

you can also omit the refetch in onSettled if your optimistic update is considered to be correct, or you can return data from the server and put that in the cache in onSuccess.

Upvotes: 2

Related Questions