Ankit
Ankit

Reputation: 1362

LocalStorage is not getting updated

This is the card.js,

import React, { useState, useEffect } from 'react'
// import { PdtList } from './Cart';
export default function Card(props) {
    let list = JSON.parse(localStorage.getItem("context"))
    const [setstyle, setsetstyle] = useState({
        color: 'black',
        background: 'rgb(238, 242, 241)'
    })
    const DeleteItem = (e) => {
        console.log("to be deleted -> ", e);
        setsetstyle({
            display: 'none'
        })
        var filteredArray = list.filter(x => x.id !== e);
        localStorage.setItem('context', JSON.stringify(filteredArray));
        list = filteredArray;
    }
    
    const { id, images, name } = props;
    return (
        <div id={id} className='align displaySet' style={setstyle} >
            <main>
                <div className="border align">
                    <img src={images} alt="" />
                    <h3>{name}</h3>
                </div>
            </main>
            <button onClick={() => DeleteItem(id)} >Delete</button>
        </div>
    )
}

The problem is when I am clicking on the Delete Button one card is getting deleted.

But when I am clicking on another card then the one I am clicking on is removed and replaced with the precious one.

I think the localStorage is reinitializing again and again

How can I resolve this?

Upvotes: 1

Views: 63

Answers (1)

Like Konrad mentioned in the comments, you should use useState to manage the state inside a React component, and then connect localStorage with a useEffect hook to only update localStorage when the value changes:

import React, { useState, useEffect } from 'react'
// import { PdtList } from './Cart';
export default function Card(props) {
    // Passing `localStorage.getItem('context')` makes the initial state the value stored in localStorage
    const [list, setList] = useState(JSON.parse(localStorage.getItem("context")))
    const [setstyle, setsetstyle] = useState({
        color: 'black',
        background: 'rgb(238, 242, 241)'
    })
    // This `useEffect` updates localStorage whenever `list` changes
    useEffect(() => {
      localStorage.setItem('context', JSON.stringify(list))
    }, [list])
    const DeleteItem = (e) => {
        console.log("to be deleted -> ", e);
        setsetstyle({
            display: 'none'
        })
        setList(list.filter(x => x.id !== e))
    }
    
    const { id, images, name } = props;
    return (
        <div id={id} className='align displaySet' style={setstyle} >
            <main>
                <div className="border align">
                    <img src={images} alt="" />
                    <h3>{name}</h3>
                </div>
            </main>
            <button onClick={() => DeleteItem(id)} >Delete</button>
        </div>
    )
}

Upvotes: 1

Related Questions