Currently, I am in the process of building an Amazon clone to enhance my understanding of Next.js. Utilizing React Context, I aim to store the selected product's ID number in an array. The data is successfully saved and accessible across all components within the project. However, a peculiar issue arises whenever a product with a two-digit ID is added – the length of the array increases by two units. Below is the snippet of my code:
import React, { createContext, useContext, useState } from 'react';
const AppContext = createContext();
export function AppWrapper({ children }) {
var [basket, addToBasket]= useState([]);
return (
<AppContext.Provider value={[basket, addToBasket]}>
{children}
</AppContext.Provider>
);
}
export function useAppContext() {
return useContext(AppContext);
}
function Product({id, title, price, description, category, image }) {
var [basket, addToBasket] = useAppContext();
const addItemToBasket = () => {
addToBasket(basket + id);
}
return(
<button onClick={addItemToBasket} className='button'>Add to Basket</button>
<h1>items ID in basket: {basket}</h1>
<h1>length of array: {basket.length}</h1>
)
Despite attempting various solutions such as:
let counter = 0;
const addItemToBasket = () => {
for (let i = 0; i < basket.length; i++) {
if (basket[i].status === '0') counter++;
};
addToBasket(basket + id);
}
...
<h1>length of array: {counter}</h1>
I have struggled to resolve this issue. My limited experience with JavaScript has led me to explore different approaches without success. Any insights or guidance on how to overcome this challenge would be greatly appreciated. Thank you for your assistance.