Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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