Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda