Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
The previous product disappear when adding new product in React local storage

I am trying to store products in local storage but when a new product is added the previous one disappears. even though I am passing an array in local storage. when I click the same product again, it updates the array, but when a new product is added previous one is disappeared.

here the code of cardInsideView:

 export default function CardInsideView() {
  
  const [CartItems, setCartItems] = useState([])
  const location = useLocation()
  const AddItemsIntoCart =()=>{
    console.log("working")
    setCartItems([...CartItems,location.state]) 
  }

  useEffect(()=>{
    if(CartItems.length){

      localStorage.setItem("items",JSON.stringify(CartItems))
    }
  },[CartItems]) 

i have 3 screens , home Screen on which Cards are displayed, card inside view screen which gets data from uselocation, and Cart Screen which shows product stored in local storage.

here is the code of CartScreen

 const getDataFromLocalStorage =()=>{
        const data = localStorage.getItem("items")
        if(data){
          return JSON.parse(data)
        }else{
          return []
        }
      }
      let data = getDataFromLocalStorage()  

remember the local storage array updates when clicking on same product but not when we add new product. when same product is clicked

when I add another new product

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this instead

setCartItems([...localStorage.getItem("items"),location.state]) 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda