Home > Software engineering >  How to fetch a value of key from localStorage and put it to input by hooks?
How to fetch a value of key from localStorage and put it to input by hooks?

Time:10-09

Sorry, I've only started learn hooks. I can't correctly write it: on page load, must be fetched from localStorage a value of key appData and puts it in the input.

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

export default function App() {
  const [appData, setValue] = useState('');
  
  useEffect(() => localStorage.setItem('appData', appData), [appData]);
 
  return (
    <div>
      React Marathon, appData: <input size='5' defaultValue={appData}></input>
    </div>
  );
}

CodePudding user response:

Just set the initial value to the localStorage value

const [appData, setValue] = useState(localStorage.getItem('appData') || '')

CodePudding user response:

import './App.css';
import { useState, useEffect } from 'react';
export default function App() {  
  const [appData, setValue] = useState("");

  useEffect(() => {
    if(!localStorage.getItem('appData')) {
      localStorage.setItem('appData', appData)
    }
  }, []);
  useEffect(() => setValue(localStorage.getItem('appData')), []);

  return (
    <div>
      React Marathon, appData: <input size='5' defaultValue={appData}></input>
    </div>
  );
}
  • Related