admin管理员组文章数量:1026989
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.
- The App needs to check localStorage when it is initialized (when browser is opened)
- 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:
- I start the React App (console does not say "Local storage is empty")
- I submit a value, console says, "Local storage is empty"
- I refresh the browser, and "Local storage is empty" message disappears
- If I add another value again, same process occurs.
What SHOULD happen (if starting with empty localStorage):
- I start the React App (console says "Local storage is empty")
- I submit a value (only one value present), no message to console
- I refresh page and still no console message
- 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.
- The App needs to check localStorage when it is initialized (when browser is opened)
- 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:
- I start the React App (console does not say "Local storage is empty")
- I submit a value, console says, "Local storage is empty"
- I refresh the browser, and "Local storage is empty" message disappears
- If I add another value again, same process occurs.
What SHOULD happen (if starting with empty localStorage):
- I start the React App (console says "Local storage is empty")
- I submit a value (only one value present), no message to console
- I refresh page and still no console message
- 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 badges1 Answer
Reset to default 1You 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);
}, []);
}
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.
- The App needs to check localStorage when it is initialized (when browser is opened)
- 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:
- I start the React App (console does not say "Local storage is empty")
- I submit a value, console says, "Local storage is empty"
- I refresh the browser, and "Local storage is empty" message disappears
- If I add another value again, same process occurs.
What SHOULD happen (if starting with empty localStorage):
- I start the React App (console says "Local storage is empty")
- I submit a value (only one value present), no message to console
- I refresh page and still no console message
- 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.
- The App needs to check localStorage when it is initialized (when browser is opened)
- 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:
- I start the React App (console does not say "Local storage is empty")
- I submit a value, console says, "Local storage is empty"
- I refresh the browser, and "Local storage is empty" message disappears
- If I add another value again, same process occurs.
What SHOULD happen (if starting with empty localStorage):
- I start the React App (console says "Local storage is empty")
- I submit a value (only one value present), no message to console
- I refresh page and still no console message
- 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 badges1 Answer
Reset to default 1You 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);
}, []);
}
本文标签: javascriptHow to check if localStorage is empty with React hooksStack Overflow
版权声明:本文标题:javascript - How to check if localStorage is empty with React hooks? - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745664610a2162101.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论