So this is the first part is from a component where i create new habitats using tanstack V5 im passing queryKey [‘habitats’]
const createHabitatMutation = useMutation({
mutationFn: habitatService.createHabitat,
onSuccess: () => {
toast({
title: 'Habitat created successfully!',
status: 'success',
duration: 5000,
isClosable: true,
});
queryClient.invalidateQueries({ queryKey: ['habitats'] })
onClose();
},
onError: (error) => {
toast({
title: 'Error creating habitat',
description: error.message || 'Please try again later.',
status: 'error',
duration: 5000,
isClosable: true,
});
},
the next part is from another components to retrieve and delete habitat im using invalidates query with the same key [‘habitats’]
const { data: habitats = [], isLoading, isError } = useQuery({
queryKey: ['habitats'],
queryFn: () => habitatService.getAllHabitats(),
onError: (error) => {
toast({
title: 'Error fetching habitats',
description: error.message,
status: 'error',
duration: 5000,
isClosable: true,
});
},
});
const deleteHabitatMutation = useMutation({
mutationFn: habitatService.deleteHabitat,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['habitats'] })
toast({
title: 'Habitat deleted',
description: 'The habitat was successfully deleted.',
status: 'success',
duration: 3000,
isClosable: true,
});
},
onError: (error) => {
toast({
title: 'Error deleting habitat',
description: error.message,
status: 'error',
duration: 5000,
isClosable: true,
});
},
The behavior I’m looking for is when I create data, it should be displayed immediately without refreshing the page. The same applies to deleting data—it should be removed instantly without needing to refresh