useEffect(()=>{
// console.log(`Ahanda items`,items)
setItems(JSON.parse(localStorage.getItem(`baskets`)) )
},[])
useEffect(()=>{
localStorage.setItem(`baskets`,`${JSON.stringify(items)}`)
},[items])
Hello i have classic async problem have. problem is there is basket for eccommerce shopping site basket simple one i want to when site is refreshing if localstorage inside have any list of product item pull and setItem but the problem is the other items Useeffect works to. So if i add timeout and do like that :
useEffect(()=>{
// console.log(`Ahanda items`,items)
setItems(JSON.parse(localStorage.getItem(`baskets`)) )
},[])
useEffect(()=>{
setTimeout(() => {
localStorage.setItem(`baskets`,`${JSON.stringify(items)}`)
}, 200);
},[items])
but the problem is not solved because some times i can be use api's
here is other explanation https://www.youtube.com/watch?v=-mTvd1O-3nM
I might get the question wrong. But please correct me. Are you looking for something like this ????
const[items, setItems] = useState([])
function handleFetchItems(){
if(localStorage.baskets){ //call this only if I have items
setItems(state =>[...state,...JSON.parse(localStorage.getItem(`baskets`))]
}
fetch(`url`).then((response) => { //async operation
setItems(state =>[...state,...response])
}).catch(() => {})
}
useEffect(useCallback(() => {handleFetchItems()},[]))
I already face This problem, and solve it by making a custom hook :
by the way, This custom hook was created by Kent creator of Remix , you can check it here : https://github.com/kentcdodds/react-hooks
usage:
const [name, setName] = useLocalStorageState({
defaultValue: 'default value',
key: 'name',
})