skip to Main Content

I’m new to React JS, I’m trying to edit some value from LocalStorage, in console I can see it has updated but I doesn’t update in the front end.
I know there are few similar threads but none is really helping me. Can someone please put me on the right direction.

// getting the values of local storage
const getDatafromLS = () => {
    const data = localStorage.getItem('reg');
    if (data) {
        return JSON.parse(data);
    }
    else {
        return []
    }
}

const Test2 = () => {

    const [regArr, setRegArr] = useState(getDatafromLS());
    const [reg, setReg] = useState({ name: "" });
    const [editForm, setEditForm] = useState(false);// edit form
    const [id, setId] = useState();// id state

    const handleChange = (e) => {
        const name = e.target.name;
        const value = e.target.value;
        setReg({ ...reg, [name]: value });
    }

    const { name } = reg;
    const handleSubmit = (e) => {
        e.preventDefault();

        if (name === "") {
            alert("INPUT can not be empty")
        } else {
            setRegArr([...regArr, { name }]);
        }
        setReg({ name: "" })
    }
    useEffect(() => {
        localStorage.setItem('reg', JSON.stringify(regArr));
    }, [regArr])

    const handleDelete = (i) => {
        let newdataArr = [...regArr]
        newdataArr.splice(i, 1)
        setRegArr(newdataArr)
    }

    const handleEdit = (i) => {
        setEditForm(true);
        setId(i);
        const data = JSON.parse(localStorage.getItem('reg'));
        setReg(data[i]);//Set the clicked record in textfield
    }
    
    const handleEditSubmit = (e) => {
        e.preventDefault();
        console.log('Checking  ', id);
    
        const newList = regArr.map(li => (
            li.id === id ? {...li, name: reg} : li)
            )
        setReg(newList)
        localStorage.setItem('reg', JSON.stringify(reg));
        setReg('');
        setEditForm(false);     
    }
    return (
        <div>
            {editForm === false && (
                <div>
                    <label>New Registration</label>
                    <input type='text' name='name' onChange={handleChange} value={reg.name} placeholder='Name ...' />
                    <button type='submit' onClick={handleSubmit}>Submit</button>
                </div>
            )}
            {editForm === true && (
                <div>
                    <label>Update Registration</label>
                    <input type='text' name='name' onChange={handleChange} value={reg.name} placeholder='Name ...' />
                    <button type='submit' onClick={handleEditSubmit}>Update</button>
                </div>
            )}
            <p></p>
            <Test3 test3={regArr} handleDelete={handleDelete} handleEdit={handleEdit} />
        </div>
    );
};

export default Test2;

I have used a seperate component for result output.

const Test3 = ({ test3, handleDelete, handleEdit }) => {

    return (
        <div>
            <table>
                <tbody>
                    {
                        test3 && test3.map((rg, index) => {
                            return (
                                <tr key={index}>
                                    <td>{rg.name}</td>
                                    <td><button onClick={() => handleDelete(index)}>Delete</button></td>
                                    <td><button onClick={() => handleEdit(index)}>Edit</button></td>
                                </tr>
                            )
                        })
                    }
                </tbody>
            </table>
        </div>
    );
};

export default Test3;

2

Answers


  1. You can use an event listener to query whether something has changed and call your function again. Or you save it directly to your state when you change it.

    window.onstorage = () => {
      console.log(JSON.parse(window.localStorage.getItem("sampleList")));
    };
    
    Login or Signup to reply.
  2. From what I understood, this makes more sens to me :

    const handleEditSubmit = (e) => {
      e.preventDefault();
      console.log('Checking  ', id);
    
      const newList = regArr.map((li) =>
        li.id === id ? { ...li, name: reg.name } : li
      );
      setRegArr(newList); // Update regArr state, not reg state
      localStorage.setItem('reg', JSON.stringify(regArr)); // Save regArr, not reg
      setReg({ name: '' }); // Clear the reg state
      setEditForm(false);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search