'How to get localStorage, createContext, withrouter and history, component from react to work on client side while using NextJs?
I am trying to get the localStorage to work but I do not know how to load the code on just the client side. Also to just have certain files run with the information from the component.
import React, { useContext } from 'react';
import { isInCart } from '../components/Helper';
import { CartContext } from '../context/cartContext';
import { withRouter } from 'next/router';
import featureP from '../styles/featureProduct.module.css';
const FeaturedProduct = (props) => {
const {title, imageUrl, price, history, id, description, priceOptions, alt,
productType} = props;
const product = { title, imageUrl, price, id, description, priceOptions,
alt, productType}
const { addProduct, cartItems, increase } = useContext(CartContext);
const itemInCart = isInCart(product, cartItems);
return (
<div className={featureP.featuredProduct}>
<div className={featureP.featuredImage} onClick={() =>
history.push(`/product/${id}`)}>
<img src={imageUrl} alt={alt} />
</div>
<div className={featureP.namePrice} />
<h3>{title} {productType}</h3>
<p>${price}</p>
{
!itemInCart && <button className={featureP.isBlack}
onClick={()=> addProduct(product)}>
Add to Cart
</button>
}
{
itemInCart && <button className={featureP.isWhite} id="btn-
white-columns" onClick={()=> increase(product)}>
Add More
</button>
}
</div>
</div>
)
}
export default withRouter(FeaturedProduct);
This is the component file I am tryin to use but the localStorage error appears. Is there a way to load this and other pages that use this content as a component but only once it is rendered on the client side. As I am using this information to get the client information for a cart.
import React, { createContext, useReducer } from 'react';
import cartReducer, { sumItems } from './cartReducer';
export const CartContext = createContext();
const cartFromStorage = localStorage.getItem('cart') ?
JSON.parse(localStorage.getItem('cart')) : [];
const initialState = { cartItems: cartFromStorage,
...sumItems(cartFromStorage)};
const CartContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
const addProduct = (product) => dispatch({type: 'ADD_ITEM', payload:
product});
const increase = (product) => dispatch({type: 'INCREASE', payload:
product});
const decrease = (product) => dispatch({type: 'DECREASE', payload:
product});
const removeProduct = (product) => dispatch({ type:'REMOVE_ITEM', payload:
product});
const clearCart = () => dispatch({ type:'CLEAR'});
const contextValues = {
...state,
addProduct,
increase,
decrease,
removeProduct,
clearCart,
}
return (
<CartContext.Provider value={ contextValues }>
{
children
}
</CartContext.Provider>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|