简体   繁体   中英

How to check if localStorage is empty with React hooks?

This is a continuation of another question I asked, Adding/deleting data into local browser storage using a button, and displaying it in a UI table (React)

I am trying to check localStorage and use an emitter to tell the console if localStorage is empty of any values.

I believe I have 2 issues.

  1. The App needs to check localStorage when it is initialized (when browser is opened)
  2. I need to use useState, so that the localStorage is checked every time a value is added/deleted

Below is my attempt (index.js):

import React,{useState} from 'react';
import ReactDOM from 'react-dom';
const EventEmitter = require('events');

const useStateWithLocalStorageArray = localStorageKey => {
  const [value, setValue] = React.useState(
    JSON.parse(localStorage.getItem(localStorageKey) || '[]' )
  );
  React.useEffect(() => {
    localStorage.setItem(localStorageKey, JSON.stringify(value))
  }, [value]);
  return [value, setValue];
};

const checkLocalStorage = function() {
  const myEmitter = new EventEmitter();
  myEmitter.on('event', () => {
    if (localStorage.getItem('customKey1') === '[]') {
      console.log('Local storage is empty');
    }
  });
  return myEmitter.emit('event');
}

const App =()=>{
  const [items,setItems] = useStateWithLocalStorageArray('customKey1')
  const [value,setValue] = useState({NAME:'',AGE:'',SALARY:''})
  const [localValue, setLocalValue] = useState('')


  const updateValue = e =>{
     setValue({...value,[e.target.id]:e.target.value})
  }


  return(
    <div>
      <div>
        <input value={value.NAME} id='NAME' placeholder='Name' onChange={(e)=>updateValue(e)}/>
        <input value={value.AGE } id='AGE' placeholder='Age' onChange={(e)=>updateValue(e)}/>
        <input value={value.SALARY} id='SALARY' placeholder='Salary' onChange={(e)=>updateValue(e)}/>
      <button onClick={()=>{
        setItems([...items,{...value}])
        setValue({NAME:'',AGE:'',SALARY:''})
        checkLocalStorage(setLocalValue)
        }}>ADD ITEM</button></div>

      <br/>
      <div>List of Items</div>
      <br/>
      { items &&
      <div>
        {
            items.map((item,index)=>(
              <li key={index}>{item.NAME}-{item.AGE}-{item.SALARY} <button onClick={()=>{
                setItems(items.filter((value,iindex) => iindex !== index))
                checkLocalStorage(setLocalValue)
              }}>Remove</button> </li>
            ))
        }
      </div>
    }
    </div>
  )
}

ReactDOM.render(<App/>, document.getElementById('root'));

I made a function checkLocalStorage() that should be called every time a value is added, or deleted:

const checkLocalStorage = function() {
  const myEmitter = new EventEmitter();
  myEmitter.on('event', () => {
    if (localStorage.getItem('customKey1') === '[]') {
      console.log('Local storage is empty');
    }
  });
  return myEmitter.emit('event');
}

But it is not working as I expect. What will happen is:

  1. I start the React App (console does not say "Local storage is empty")
  2. I submit a value, console says, "Local storage is empty"
  3. I refresh the browser, and "Local storage is empty" message disappears
  4. If I add another value again, same process occurs.

What SHOULD happen (if starting with empty localStorage):

  1. I start the React App (console says "Local storage is empty")
  2. I submit a value (only one value present), no message to console
  3. I refresh page and still no console message
  4. I delete a value, "Local storage is empty" message appears in console

I believe I am not using React hooks properly, I initialized the hook:

const [localValue, setLocalValue] = useState('')

I then try to use it like this inside const App :

checkLocalStorage(setLocalValue)

I am not sure, what I am doing wrong, like I said before, I think I am not using hooks correctly, if more information is needed, please let me know.

You can use "onstorage" event to check when it updates. For example on root of your app:

window.addEventListener('storage', event => {
  // event contains
  // key – the key that was changed
  // oldValue – the old value
  // newValue – the new value
  // url – 
  // storageArea – either localStorage or sessionStorage object where the update happened.
});
const useStorage = (storageName) => {

  const checkStorage = key => {
     const storedData = localStorage.getItem(key);
     if (!storedData) console.log('Local storage is empty');
  }

  useEffect(() => {
   // when app loaded
   checkStorage(storageName)

    // when storage updated
    const handler = ({key}) => checkStorage(key);
    window.addEventListener('storage', handler);
    retunr () => window.removeEventListener('storage', handler);
  }, []);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM