What causes my JavaScript array to grow by two when I insert a number with two digits?

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.

Answer №1

useState doesn't return a pusher, but rather a getter and a setter. Your addToBasket function mistakenly sets the value of the basket property to (basket + id), resulting in a string. Essentially, while basket starts as an array, using the + operator on non-numeric values will convert it into a string; once this happens, adding id will simply append its string representation to the existing one.

To correct this issue:

const [basket, setBasket] = useState([]);

const addItemToBasket = () => {
  setBasket([...basket, basket + id]);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

Having trouble getting CSS absolute and relative positioning to work with my div slider carousel

I'm currently working on creating a slider carousel using VUE, where the CSS classes (3 divs) are looped through. However, I am facing an issue where every time a div fades out, the next slider creates a duplicate slider at the bottom, resulting in tw ...

Is it just me, or is there a strange glitch with emojis: sharing the same ID and name, yet having different skin

Working with emoji is usually smooth sailing for me, but I've hit a roadblock with a stubborn bug. My script is designed to detect emoji and replace them, but there's a strange glitch with a few specific ones. Sometimes, the emoji appears differe ...

The process of incorporating external JavaScript scripts into VueJS Components

I currently have two external scripts that need to be used for the payment gateways. At the moment, both scripts are placed in the index.html file. However, I prefer not to load these files at the beginning of the process. The payment gateway is only re ...

A continuous bark emitted by the howler.js will not acknowledge commands to stop

Currently, I am facing a challenging situation in my React/Next.js application where a single play command using Howler.js does not pause or stop properly. Despite my efforts to troubleshoot the issue, I am unable to determine the underlying cause. Below ...

Synchronize movie subtitles with precision using javascript

Currently, I am facing a challenge with syncing my JSON subtitle with an iframe video from YouTube. Unlike the typical formats such as vtt and srt, I prefer writing my subtitles in JSON format. My main query revolves around how to accurately sync my JSON ...

Generate a Swagger file effortlessly for your Node.js application

Currently, I am working on a Node Express RESTful API built with TypeScript. I would like to know if there is a tool available that can generate a Swagger file automatically for my project based on the source code. Thank you! ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Encountering a hydration issue in Next.js 13 due to applying initial framer-motion animation value conditionally depending on the screen size

In my Next.js 13 app, I am utilizing framer-motion for animations on a single-page layout with multiple screens. Navigation is achieved by scrolling to their respective section IDs, and I am using the traditional pages directory. One of the screens featur ...

A guide to setting defaultValue dynamically in React Hook Form

Presently, I am facing an issue with editing the Product page. The props values are fetched through an API and sent from the parent component. However, I am struggling to set this value to my Datepicker input. This is because the defaultValue function from ...

What benefits does invoking the .call() method on Observable functions offer?

I am new to Angular and finding it challenging to comprehend some code I came across in the ng-bootstrap project. You can find the source code here. The section that particularly confuses me is the ngOnInit method: ngOnInit(): void { const inputValue ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

Initializing Three.js to load the model

I have a 3D model that I initially had in the 3DS format. I then converted it to OBJ and finally to JS format. Now, my goal is to load this model into another JS file. Below you'll find the code snippet I've written for this purpose: var loader ...

Determine if an array of objects within React JS contains additional objects

I need assistance in displaying the <div className="songs-list-header-col">Album</div> only if the tracks array contains the artist property as an object. In cases where the artist is not an object, I do not want to display the <di ...

A new WordPress tool for transferring information seamlessly between jQuery and PHP before storing it in a database

Having recently delved into this subject, I decided to experiment with the following example: I created a new folder within the plugins directory called "abc-referer" In that folder, I made a PHP file named "abc-referer.php" and included the following PH ...

Refreshing a page will disable dark mode

I'm in the process of implementing a dark mode for my website using the code below. However, I've encountered an issue where the dark mode resets when refreshing the page or navigating to a new page. I've heard about a feature called localst ...

Steps for saving both checked and unchecked checkbox values in Firebase

I have a set of objects that I am using as initial data in my Ionic 3 application: public interests = [ { name: 'Travel', checked: false }, { name: 'Animals', checked: false }, { name: 'Theatre', checked: false ...

Enter key not activating keycode trigger as expected

Trying to utilize the keycode to activate a button click on enter key press. The current code functions properly when an alert is inserted in the keycode function, but does not work as intended when placed inside the .click(function.... Unsure of the missi ...

Obtain the recovery path for the 'img' src

Here is the code snippet that I am working with: <table> <tr> <td> <img src='prod/images/1.jpg'> </td> </tr> <tr> <td> <img src=' ...