Home > Back-end >  How maltiple value using usestate localstorage in react?
How maltiple value using usestate localstorage in react?

Time:07-14

I want to work using maltiple values in use state and crud in local storage use state like const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }] ]

And it updates with the form
<input>

// .......

if value true  Display  take look at this example I try but I cannot do how to solve it

import './App.css'; import React, { useState,useEffect } from 'react';

function App() {
  const [User, setUser] = useState([
    {
      Name:'',
      Pass:'',
      Email:'',
    }
  ]);

 
  const [storedUser,setstoredUser]=useState([])

  
  const handle = () => {

     localStorage.setItem(JSON.stringfy(...User))
    
     setstoredUser(...User);

  };
  const remove = () => {
     localStorage.removeItem();

  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            name='Name'
            value={User.Name}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            name="Pass"
            placeholder="Password"
            value={User.Pass}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
           <h1>Email of the user:</h1>
          <input
            type="mail"
            name="Email"
            placeholder="Email"
            value={User.Email}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {storedUser.Name && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {storedUser.Pass && (
            <div>
               Password: <p>{localStorage.getItem('Pass')}</p>
            </div>
         )}
          {storedUser.Email && (
            <div>
               Password: <p>{localStorage.getItem('Email')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;

Here I try how to do this formate I try to all data in state and stringify set this local storage. then remove and display I think explaine on detail

CodePudding user response:

You're missing the key

localStorage.setItem("User",JSON.stringfy(...User))

If you want each key. Loop over they keys and values and set them

Object.entries(User).forEach(([key,value])=>{
      localStorage.setItem(key,value)
    })

CodePudding user response:

Since User already is an array of user objects I wouldn't spread them in your handle function. You also need to set a key if you're saving in localStorage. This is how to save your list of users under "users":

const handle = () => {
  localStorage.setItem("users", JSON.stringfy(User));
  setstoredUser(User);
};

Now when retrieving users from the localStorage you can make use of JSON.parse like this:

users = JSON.parse(localStorage.getItem("users") || "[]");

And for deletion you would need the key "users" here as well:

localStorage.removeItem("users");

CodePudding user response:

You are doing a few things incorrectly here:

  • you are not providing a key for local storage
  • you don't need to spread objects directly inside set state
  • you need to provide a key to local storage
  • use the clear method to clear local storage
  • you are setting the user as an array to state not an object, this is unnecessary in the example you have

If the goal is to persist a single user between sessions via local storage. Then all you need to do is save the user to local storage when the form is submitted. Then, when the component loads, check local storage for user data.

import { useEffect, useState } from 'react'

function App() {
  const [User, setUser] = useState({
    Name: '',
    Pass: '',
    Email: '',
  })

  const handle = () => {
    const nextUser = JSON.stringify(User)
    localStorage.setItem('user', nextUser)
  }
  const remove = () => {
    localStorage.clear()
  }

  useEffect(() => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      setUser(JSON.parse(storedUser))
    }
  }, [])
  return (
    <div className="App">
      <h1>Name of the user:</h1>
      <input
        placeholder="Name"
        name="Name"
        value={User.Name}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <h1>Password of the user:</h1>
      <input
        type="password"
        name="Pass"
        placeholder="Password"
        value={User.Pass}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <h1>Email of the user:</h1>
      <input
        type="mail"
        name="Email"
        placeholder="Email"
        value={User.Email}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <div>
        <button onClick={handle}>Done</button>
      </div>

      {User.Name && (
        <div>
          Name: <p>{User.Name}</p>
        </div>
      )}
      {User.Pass && (
        <div>
          Password: <p>{User.Pass}</p>
        </div>
      )}
      {User.Email && (
        <div>
          Password: <p>{User.Email}</p>
        </div>
      )}
      <div>
        <button onClick={remove}>Remove</button>
      </div>
    </div>
  )
}

export default App
  • Related