4

I'm doing this code from a blog example as local storage with react .but it doesn't work in real-time after refreshing it. how can I do it in real-time? I think it can use the effect hook used to be solved but I cannot implement it, does anybody help me with this solution

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

function App() {
  
  const [name, setName] = useState('');
  const [pwd, setPwd] = useState('');
  
 
  
  const handle = () => {
     localStorage.setItem('Name', name);
     localStorage.setItem('Password', pwd);
  };
  const remove = () => {
     localStorage.removeItem('Name');
     localStorage.removeItem('Password');
  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            placeholder="Password"
            value={pwd}
            onChange={(e) => setPwd(e.target.value)}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {localStorage.getItem('Name') && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {localStorage.getItem('Password') && (
            <div>
               Password: <p>{localStorage.getItem('Password')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;
    

This code has no problem but I want to work with real-time when I click done it shows real-time how do I?

nullptr
  • 3,701
  • 2
  • 16
  • 40
Luis swift
  • 65
  • 1
  • 6

3 Answers3

3
  • Don't reference local storage in your render, use state.
  • Initialize state to local storage value.
  • On update, update both state and local storage.
JBallin
  • 8,481
  • 4
  • 46
  • 51
1

You can use useState to handle local storage in real-time.

Side note that the below implementation is just for demonstration, you SHOULD NOT store passwords in local storage at ALL COST!

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

function App() {
  
  const [name, setName] = useState('');
  const [pwd, setPwd] = useState('');
  const [storedName, setStoredName] = useState(localStorage.getItem('Name'));
  const [storedPassword, getStoredPassword] = useState(localStorage.getItem('Password'));
  
  const handle = () => {
     localStorage.setItem('Name', name);
     localStorage.setItem('Password', pwd);
     setStoredName(name);
     setStoredPassword(pwd);
  };
  const remove = () => {
     localStorage.removeItem('Name');
     localStorage.removeItem('Password');
     setStoredName('');
     setStoredPassword('');
  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            placeholder="Password"
            value={pwd}
            onChange={(e) => setPwd(e.target.value)}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {storedName && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {storedPassword && (
            <div>
               Password: <p>{localStorage.getItem('Password')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;

If you want to understand why we should not store passwords in local storage, you can check this article

Storing something sensitive like a password in a local storage file actually simplifies the process for a hacker, because they won’t need to load the cookie into their own browser.

Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • @Luisswift if my answer is useful, please upvote or mark my answer as a solution, that would show a little support towards me as well as this community. Thank you :D – Nick Vu Jul 09 '22 at 06:16
  • It's bits of help, I try to like this good optimization, do you have any idea how to protect my password when it saves in local storage ... it helps very much for I searching for that solution if you now kindly note me ..i mean without fire base and node js is it possible !@nickvu – Luis swift Jul 11 '22 at 14:59
  • you can try to encrypt values (hiding the true identities of your keys and values) and decrypt values (comparing the true values) - Check [this thread](https://stackoverflow.com/questions/18279141/javascript-string-encryption-and-decryption), but it's not fully secured if somebody tries to read your data in localstorage. @Luisswift – Nick Vu Jul 11 '22 at 15:13
0

if you want to use hook

import React, { useState, useEffect } from "react";

export function useUserHook() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [change, setChange] = useState(false);

  React.useEffect(() => {
    const loadSaved = async () => {
      setName(localStorage.getItem("Name"));
      setPassword(localStorage.getItem("Password"));
    };
    loadSaved();
  }, [name, password, change]);

  const saveData = async (name, password) => {
    setChange(!change);
    await localStorage.setItem("Name", name);
    await localStorage.setItem("Password", password);
  };

  const removeData = async () => {
    setChange(!change);
    await localStorage.removeItem("Name");
    await localStorage.removeItem("Password");
  };

  return {
    name,
    password,
    saveData,
    removeData
  };
}

import hook to App.js

import { useUserHook } from "./userHook";

add some changes in the code

import React, { useState, useEffect } from "react";
import { useUserHook } from "./userHook";
import "./styles.css";

const App = () => {
  const { name, password, saveData, removeData } = useUserHook();
  const [nameState, setName] = useState("");
  const [pwdState, setPwd] = useState("");

  const handle = () => {
    console.log("do save");
    saveData(nameState, pwdState);
  };
  const remove = () => {
    console.log("do remove");
    removeData();
  };
  return (
    <div className="App">
      <h1>Name of the user:</h1>
      <input
        placeholder="Name"
        value={nameState}
        onChange={(e) => setName(e.target.value)}
      />
      <h1>Password of the user:</h1>
      <input
        type="password"
        placeholder="Password"
        value={pwdState}
        onChange={(e) => setPwd(e.target.value)}
      />
      <div>
        <button onClick={handle}>Done</button>
      </div>
      {name && (
        <div>
          Name: <p>{name}</p>
        </div>
      )}
      {password && (
        <div>
          Password: <p>{password}</p>
        </div>
      )}
      <div>
        <button onClick={remove}>Remove</button>
      </div>
    </div>
  );
};

export default App;

I hope it can help you

FAOZI
  • 67
  • 6
  • It's bits of help, I try to like this good optimization, do you have any idea how to protect my password when it saves in local storage ... it helps very much for I searching for that solution if you now kindly note me @FAOZI – Luis swift Jul 11 '22 at 06:03