I am new in react, and wanted to make a shopping website. I created a global array named cart, and I can read the data in it. However, when I tried to update the data in the cart array, I encountered with the error "ReferenceError: cart is not defined"
const [cartProducts, setCartProducts] = useState(cart);
const handleCartButton = () => {
if(!cartProducts.includes({item})) // itemi içerse de buraya giriyor.
{
const newList = cartProducts.concat( [{item}] );
setCartProducts(newList);
}
cart = cartProducts; // this is the error line
}
useEffect(()=>{
console.log(item.name cartProducts);
console.log(cart);
},[cartProducts])
and this is the cart array,
export let cart = [];
I do not know how to update a global variable.
CodePudding user response:
For global variables you should use context
// AppContext.js
import React, { useContext } from "react"
const AppContext = React.createContext()
export const AppProvider = ({
children
}) => {
const [cart, setCart] = useState([])
const value = { cart, setCart }
return <IconContext.Provider value={value}>{children}</IconContext.Provider>
}
export function useAppContext() {
return useContext(AppContext)
}
And then use it like this (from your example):
// make sure to import useAppContext
const { cart, setCart } = useAppContext()
const handleCartButton = () => {
if(!cart.includes({item})) {
const newList = cart.concat( [{item}] );
setCart(newList);
}
}
useEffect(()=>{
console.log(item.name cart);
console.log(cart);
},[cart])
And then make sure to wrap your component in AppProvider:
import React from "react"
import {AppProvider} from "./AppContext.js"
const ParentComponent = () => {
return <AppProvider>
<YourComponent/>
</AppProvider>
}
You can wrap your whole application with AppProvider:
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {AppProvider} from "./AppContext.js"
const root = ReactDOM.createRoot(
document.getElementById('root')
);
root.render(
<React.StrictMode>
<AppProvider>
<App />
</AppProvider>
</React.StrictMode>
);