Skip to content

Instantly share code, notes, and snippets.

@buglessir
Created February 28, 2022 07:32
Show Gist options
  • Save buglessir/fd856712c4bbc3e4e335caa0e02a2631 to your computer and use it in GitHub Desktop.
Save buglessir/fd856712c4bbc3e4e335caa0e02a2631 to your computer and use it in GitHub Desktop.
An example for the Query Object in react-query
// (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