Reputation: 356
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.
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:
What SHOULD happen (if starting with empty localStorage):
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.
Upvotes: 1
Views: 12776
Reputation: 111
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);
}, []);
}
Upvotes: 1