An example for the Query Object in 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
// (1) ----------> Query Object for the useQuery(); | |
import { fetchListFunction } from './services'; | |
export const FetchListObj = (key, config) => ({ | |
queryKey: ['FetchList', key], | |
queryFn: () => fetchListFunction, | |
placeholderData: { | |
list: [] | |
}, | |
...config, | |
}); | |
// (#) ----------> How to use it in Component? | |
import { useQuery } from 'react-query'; | |
import { FetchListObj } from 'api/rq-objects'; | |
const List = () => { | |
const { data, error, isFetching } = useQuery(FetchListObj('string or object...', YourCustomConfigs)); | |
. | |
. | |
. | |
return ( ...... ); | |
} | |
// (2) ----------> Query Object for the useMutation(); | |
import { createPostFunction } from './services'; | |
export const CreatePostObj = (config) => ({ | |
mutationFn: createPostFunction, | |
mutationKey: 'CreatePost', | |
...config, | |
}); | |
// (#) ----------> How to use it in Component? | |
import { useMutation } from 'react-query'; | |
import { CreatePostObj } from 'api/rq-objects'; | |
const Post = () => { | |
const createPost = useMutation(CreatePostObj({ | |
onSuccess: // Custom onSuccess Function (show toast message or redirect e.g), | |
appQueryClient.invalidateQueries(/* Custom necessary Cache Invalidation command (refresh list e.g) */); | |
})); | |
const handleNewPost = () => { | |
createPost.mutate( /* {...values} */ ); | |
} | |
. | |
. | |
. | |
return ( ...... ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment