'dom is not updated after state change via Context API
I am quite new to React and tried to finish a project on FrontendMentor. It's basically a simple OPA of an online store with just one product and the ability to add this product to a cart.
I thought it would be a good idea to learn about Reacts Context API so that I get a basic understanding.
The first context that I created basically looks like this:
import { createContext, useContext, useState } from "react";
export const CartContext = createContext();
export const CartProvider = ({ children }) => {
const cartValue = useCartProvider();
return (
<CartContext.Provider value={cartValue}>{children}</CartContext.Provider>
);
};
export const useCart = () => {
return useContext(CartContext);
};
export const useCartProvider = () => {
const initialValue = [{name: name, price: price, amount: amount}];
const [cartAmount, setCartAmount] = useState(initialValue);
const addToCart = (name, price, amount) => {
setCartAmount([
...cartAmount,
{ name: name, price: price, amount: amount },
]);
};
return {
cartAmount,
setCartAmount,
addToCart,
};
};
When I add something to the Cart, I want to display the current amount of products in the cart with a little number above the cart. I implemented everything to the point that I see the number and can access the state variable cartAmount
in the Navbar component.
Unfortunately it does not update. When I add to the cart I can console.log the event but the badge above the cart is not being updated.
Also - the update does not happen in real time.
I've read about Reacts ability to badge state updates for performance reasons and I also read about using useReducer
hook for the actions.
With my current knowledge I feel like I cannot make the connection between all of these elements, yet.
Would like your help on that - please let me know if you need more information than provided.
Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|