TanStackT
TanStack3y ago
4 replies
progressive-amaranth

How to use React Query with React's Context API

I am attempting to refactor a Provider component, where state is being handled, e.g.

const [products, setProducts] = useState<Product[]>([]);

const {
    data: fetchedProducts,
    isFetching: isProductsFetching,
    isLoading: isProductsLoading,
    refetch: refetchProducts,
  } = useQuery({
    queryKey: ['products'],
    queryFn: () =>
      getProducts()
        .then((res) => res.json())
        .then((response: getProductsResponse) => response.data),
});


Below are examples of functions which are CRUD operations:

const addNewProduct = (product: Product): void => {
  setProducts(addProduct(products, product));
};

const getAProductById = (productId: string) => getProductById(products, productId);

const deleteAProduct = (productId: string) => {
  setProducts(products.filter((product) => product.productId !== productId));
};


My understanding is to be able to refactor this would involve the use of the useMutation hook. However, I am not sure where to start and any pointers/examples would be very much appreciated!
Was this page helpful?