I'm learning react and using context for the first time. I'm trying to pass a state and setState function through context to all children components, and I keep getting an error.
This is how I'm creating the context:
import {createContext} from 'react'
const Context = createContext({
wishlist: [],
setObject: () => {}
});
export default Context
This is where I create the useState hook and pass the context on to children components:
const [wishList, setwishList] = useState ([])
return (
<div className={darkMode === false ? 'lightMode' : 'darkMode'}>
<Router>
<Context.Provider value={{wishList, setwishList}} >
<Header setDarkMode={setDarkMode} darkMode={darkMode} wishListcounter={wishListcounter} productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
<Switch>
<Route path='/' exact>
<Hero darkMode={darkMode} productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
</Route>
<Route path='/gallery'>
<Gallery darkMode={darkMode} productsDataBase={productsDataBase} productsArray={productsArray} setProductsArray={setProductsArray} wishListcounter={wishListcounter} setwishListcounter={setwishListcounter}/>
</Route>
<Route path='/item'>
<Item />
</Route>
<Route path='/wishlist'>
<Wishlist wishListcounter={wishListcounter} />
</Route>
<Route path='/about'>
<About productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
</Route>
</Switch>
<Footer />
</Context.Provider>
</Router>
</div>
); }
And this is where I consume the context, read the state and modify it.
// Hook used to access wishlist and modify it
const {wishList, setwishList} = useContext(Context)
function handleWishClick (id) {
wishList.includes(id) ? wishList.splice(wishList.indexOf(id), 1) : setwishList(wishList.push(id))
console.log(wishList)
}
The error I'm getting is TypeError: wishList.includes is not a function. And this only happens once the state has been modified once.
I mean, the handleWishClick function runs well once, but when I try to run it again then the state doesn't get recognized.
Any tips on how to solve this?
Full code can by found here: https://github.com/coccagerman/sweetKicks
Thanks in advance!