最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to check if localStorage is empty with React hooks? - Stack Overflow

matteradmin9PV0评论

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.

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.

Share Improve this question edited Mar 24, 2020 at 3:06 W. Churchill asked Mar 22, 2020 at 0:24 W. ChurchillW. Churchill 3561 gold badge11 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

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);
  }, []);
}
Post a comment

comment list (0)

  1. No comments so far