Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

0

Try this instead

setCartItems([...localStorage.getItem("items"),location.state]) 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!