PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How maltiple value using usestate localstorage in react?

 July 24, 2022     arrays, javascript, json, local-storage, reactjs     No comments   

Issue

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


Solution

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 setState
  • use the removeItem method to clear the user from localStorage
  • 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.removeItem('user')
  }

  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


Answered By - Ollie
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing