Created
September 24, 2023 08:36
-
-
Save pingrishabh/accf8cb5a3cf2b04b101040cb1c59cb6 to your computer and use it in GitHub Desktop.
Simple hook to perform optimistic updates with react-query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback } from "react"; | |
import { useQueryClient } from "@tanstack/react-query"; | |
export default function useOptimisticUpdate() { | |
const queryClient = useQueryClient(); | |
return useCallback( | |
async (queryKey, updater) => { | |
await queryClient.cancelQueries({ queryKey }); | |
const previous = queryClient.getQueryData(queryKey); | |
queryClient.setQueryData(queryKey, updater); | |
return previous; | |
}, | |
[queryClient], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment