Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

77
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

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this instead

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