Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
react useEffect async triggering eachother problem how solve you guys?
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

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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()},[]))
about 4 years ago · Santiago Gelvez Report

0

I already face This problem, and solve it by making a custom hook :

enter image description here

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',
})
  • name is the value stored under the key 'name' in localStorage
  • setName is the setter of the new data in key 'name' in localStorage
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!