Home > front end >  when i console.log(function) one page to another page its gives me undefined value on the other page
when i console.log(function) one page to another page its gives me undefined value on the other page

Time:12-18

when i console.log(function) one page to another page its gives me undefined value on the other page but on the real page it gives me real value. how to solve it in nextjs

function MyApp({ Component, pageProps}) {
  const [cart, setCart] = useState({}) 
  const [subTotal, setSubTotal] = useState(0)
  useEffect(() => {
    console.log("hey i am a use effect from app .js")
      try {
        if(localStorage.getItem("cart")){
          setCart(JSON.parse(localStorage.getItem("cart")))
        }
      } catch (error) {
        console.error(error);
        localStorage.clear()
      }
  }, [])
  
  const saveCart = (myCart) => {
    localStorage.setItem("cart",myCart)
    let subt = 0;
    let keys = Object.keys(cart)
    for(let i = 0; i<keys.lenght; i  ){
      subt  = myCart[keys[i]].price * myCart[keys[i]].qty;
    }
    setSubTotal(subt)
  }

  const addToCart = (itemCode, qty, price,name,size,variant) => {
    let newCart = cart;
    if(itemCode in cart){
      newCart[itemCode].qty = cart[itemCode].qty   qty; 
    } else {
      newCart[itemCode] = {qty:1,price,name,size,variant}
    }
    setCart(newCart)
    saveCart(newCart)
  }

  const clearCart = () => {
    setCart({})
    saveCart({})
  }

  const removeFromCart = (itemCode, qty, price,name,size,variant) => {
    let newCart = cart;
    if(itemCode in cart){
      newCart[itemCode].qty = cart[itemCode].qty - qty; 
    }
    if(newCart[itemCode]["qty"]<=0){
      delete newCart[itemCode]
    }
    setCart(newCart)
    saveCart(newCart)
  }
  useEffect(()=>{
    const mode = localStorage.getItem("mode");
     if(mode){
       document.documentElement.classList.add("dark");
     }
   },[])
  return (
    <Layout {...pageProps} cart={cart} saveCart={saveCart} addToCart={addToCart} clearCart={clearCart} removeFromCart={removeFromCart} subTotal={subTotal}>
      <Component {...pageProps} />
    </Layout>
  );
}

export default MyApp

this is the main page

const  NavBarTop2 = ({cart,saveCart,addToCart,clearCart,removeFromCart,subTotal}) => {
    console.log(cart,saveCart,addToCart,clearCart,removeFromCart,subTotal)
    return (
        <div className="nav_top2">
        </div>
    )
}
export default NavBarTop2;

this is an other page where I want to use them but its gives me undefined variables if anyone knows please help me out this problem

CodePudding user response:

For something like this you should create a react context provider. Using a context provider also allows you to access these functions in any component that is wrapped inside the provider without unnecessary prop drilling. https://reactjs.org/docs/context.html

This is due to how props work for page components in NextJS. You can read more about how NextJS page props work here: https://nextjs.org/docs/basic-features/pages

// CartProvider.jsx
import { createContext,  useMemo, useState, useContext } from "react"

const CartContext = createContext(null)

export const useCart = () => useContext(CartContext)

const CartProvider = ({ children }) => {
    const [cart, setCart] = useState({}) 
    const [subTotal, setSubTotal] = useState(0)
    
    const saveCart = (myCart) => {
      localStorage.setItem("cart",myCart)
      let subt = 0;
      let keys = Object.keys(cart)
      for(let i = 0; i<keys.lenght; i  ){
        subt  = myCart[keys[i]].price * myCart[keys[i]].qty;
      }
      setSubTotal(subt)
    }
  
    const addToCart = (itemCode, qty, price,name,size,variant) => {
      let newCart = cart;
      if(itemCode in cart){
        newCart[itemCode].qty = cart[itemCode].qty   qty; 
      } else {
        newCart[itemCode] = {qty:1,price,name,size,variant}
      }
      setCart(newCart)
      saveCart(newCart)
    }
  
    const clearCart = () => {
      setCart({})
      saveCart({})
    }
  
    const removeFromCart = (itemCode, qty, price,name,size,variant) => {
      let newCart = cart;
      if(itemCode in cart){
        newCart[itemCode].qty = cart[itemCode].qty - qty; 
      }
      if(newCart[itemCode]["qty"]<=0){
        delete newCart[itemCode]
      }
      setCart(newCart)
      saveCart(newCart)
    }

    const providerValue = useMemo(() => ({
        cart,
        saveCart,
        addToCart,
        clearCart,
        removeFromCart,
        subTotal,
    }),[])

    return (
        <CartContext.Provider value={providerValue}>
            { children }
        </CartContext.Provider>
    )
  }
  
export default CartProvider

// _app.jsx
import CartProvider from './CartProvider.jsx'
export default function MyApp({ Component, pageProps }) {
  return (
      <CartProvider>
          <Component {...pageProps} />
      </CartProvider>
)}
// NavBarTop2.jsx
import { useCart } from './CartProvider'

const NavBarTop2 = () => {
    const {
        cart,
        saveCart,
        addToCart,
        clearCart,
        removeFromCart,
        subTotal,
    } = useCart()

   return ( //return here )

}

CodePudding user response:

Controll from where you are using "NavBarTop2", the undefined in the console.log means that you are not passing anything to NavBarTop2.

Is not that the functions defined in your main are than automatically available.

  • Related