skip to Main Content

I can’t figure out what’s going on. I add an object to the array, it is added, but the old data copies the values from the new object. This is the first time I’ve encountered this.

Here is the code

      var news = []
      var next
      if(cart === null){
        next = 0
      }else {
        next = cart.length
      }
      switch(type){
        case 'horizontal':
          config['0']['type'] = type
          config['0']['id'] = next
          config['0'].idImg = selectSvg
          if(cart === null || cart === undefined || cart.length < 1){
            news.push(config)
            setCountCart(news.length)
            localStorage.setItem('cart-tagstyle', JSON.stringify(news))
            setCart(news)
          }else {
            var news = cart.slice()
            console.log(news);
            news.push(config)
            console.log(news);
            setCountCart(news.length)
            localStorage.setItem('cart-tagstyle', JSON.stringify(news))
            setCart(news)
          }
          break;

I tried it without push, according to the following index, the same thing. I searched the Internet, it didn’t help. I’ve been suffering for the second day

2

Answers


  1. config['0']['type'] = type
    config['0']['id'] = next
    config['0'].idImg = selectSvg
    

    Due to this old data copies value from new objects. Check the below code where the index is changed

    config[next]['type'] = type
    config[next]['id'] = next
    config[next].idImg = selectSvg
    
    Login or Signup to reply.
  2. if I understand the problem correctly,
    the problem is that because arrays are reference types. Which means when you assign an array to a variable, you’re assigning a memory address and not the actual array itself,
    so you should use deep clone for solving that or use

    const newArray = [...oldArray];
    

    than changing newArray will not effects oldArray

    checkout this link for more info
    https://dev.to/samanthaming/how-to-deep-clone-an-array-in-javascript-3cig

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search