Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context is undefined #6207

Closed
nicitaacom opened this issue Oct 20, 2023 · 0 comments
Closed

context is undefined #6207

nicitaacom opened this issue Oct 20, 2023 · 0 comments

Comments

@nicitaacom
Copy link

nicitaacom commented Oct 20, 2023

Describe the bug

I got context undefined when I tried to use it

//Decrease product quantity
  const { mutate: decreaseProductQuantity, isPending: isPendingDecreaseProductQuantity } = useMutation({
    mutationFn: async () => {
      const updated_cart_quantity: number | undefined = queryClient.getQueryData(["cart_quantity"])
      const updated_cart_products: ICartProduct[] | undefined = queryClient.getQueryData(["cart_products"])

      /* update cart_products and cart_quantity in DB */

      const { error: cart_quantity_error } = await supabaseClient
        .from("users_cart")
        .update({ cart_quantity: updated_cart_quantity })
        .eq("id", userStore.userId)
      if (cart_quantity_error) throw cart_quantity_error

      const { error: cart_products_error } = await supabaseClient
        .from("users_cart")
        .update({ cart_products: updated_cart_products })
        .eq("id", userStore.userId)
      if (cart_products_error) throw cart_products_error
    },
    onMutate: () => {
      /* logic to update cart_quantity optimistically */
      //update cart_quantity first
      const cart_quantity: number | undefined = queryClient.getQueryData(["cart_quantity"])
      let updated_cart_quantity = cart_quantity
      if (cart_quantity === 0) {
        return cart_quantity
      } else if (updated_cart_quantity !== undefined) {
        updated_cart_quantity -= 1
      }

      /* logic to update cart_products optimistically */
      const cart_products: ICartProduct[] | undefined = queryClient.getQueryData(["cart_products"])
      let updated_cart_products = cart_products
      if (productQuantity === 0) {
        return productQuantity
      } else if (updated_cart_products !== undefined) {
        updated_cart_products[
          updated_cart_products?.findIndex(productInCart => productInCart.id === product.id)
        ].quantity -= 1
        //leave products in cart only if product.quantity > 0
        updated_cart_products = updated_cart_products.filter(productInCart => productInCart.quantity > 0)
        setProductQuantity(productQuantity - 1)
      }

      queryClient.setQueryData(["cart_quantity"], updated_cart_quantity)
      queryClient.setQueryData(["cart_products"], updated_cart_products)
    },
    onError: () => {
      /* logic to rollback cart_quantity */
      //update cart_quantity first
      const cart_quantity: number | undefined = queryClient.getQueryData(["cart_quantity"])
      let updated_cart_quantity = cart_quantity
      if (updated_cart_quantity === 0) {
        return cart_quantity
      } else if (updated_cart_quantity !== undefined) {
        updated_cart_quantity += 1
      }

      /* logic to rollback cart_products */
      const cart_products: ICartProduct[] | undefined = queryClient.getQueryData(["cart_products"])
      let updated_cart_products = cart_products
      if (productQuantity === 0) {
        return productQuantity
      } else if (updated_cart_products !== undefined && productQuantity + 1 === 1) {
        //no way to rollback this because I setProductQuantity(1-1)
      } else if (updated_cart_products !== undefined) {
        updated_cart_products[
          updated_cart_products.findIndex(productInCart => (productInCart.id = product.id))
        ].quantity += 1
        setProductQuantity(productQuantity + 1)
      }

      queryClient.setQueryData(["cart_quantity"], updated_cart_quantity)
      queryClient.setQueryData(["cart_products"], updated_cart_products)
    },
  })

So I do this logic to rollback on error - with context it would be easer

Your minimal, reproducible example

example

Steps to reproduce

Here it works (I can get access to context)

const {
    mutate: decreaseOnStockQuantity,
    isPending: decreaseOnStockQuantityPending,
    context: decreaseOnStockQuantityContext,
  } = useMutation({
    mutationFn: async () => {
      throw Error("something went wrong")
      await supabase.from("products").update({ on_stock: onStock }).eq("id", "123")
    },
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ["userToDos"] })
      const previousState: IProduct[] | undefined = queryClient.getQueryData(["userToDos"])
      if (previousState) {
        const updatedState = previousState
        updatedState[0].on_stock -= 1

        console.log(31, "updatedState - ", updatedState)
        setOnStock(updatedState[0].on_stock)
        queryClient.setQueryData(["userToDos"], updatedState)
        return { updatedState }
      }
    },
    onSuccess: () => {
      toast({ title: "success", description: "task updated" })
      queryClient.invalidateQueries({ queryKey: ["userToDos"] })
    },
    onError: error => {
      setOnStock(decreaseOnStockQuantityContext?.updatedState[0].on_stock ?? on_stock)
      queryClient.setQueryData(["userToDos"], () => decreaseOnStockQuantityContext?.updatedState)
      toast({ title: "error", description: error.message, variant: "destructive" })
    },
    onSettled: () => {
      // toast({ title: "onSettled", description: "onSettled description" })
      queryClient.invalidateQueries({ queryKey: ["userToDos"] })
    },
  })

So to reproduce it you may git clone repo where I write this code
https://github.com/nicitaacom/23_store/blob/development/app/(site)/components/Product.tsx

And console.log(context)
and you got undefined (also you need .env so set up supabase if you want or just trust me)

Expected behavior

I want to use context
But I got context undefined

How often does this bug happen?

Sometimes

Screenshots or Videos

No response

Platform

v5

Tanstack Query adapter

react-query

TanStack Query version

v5

TypeScript version

latest

Additional context

You may move it to discussions if you want to
I think its bug because I do similar things

@TkDodo TkDodo closed this as not planned Won't fix, can't repro, duplicate, stale Oct 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants