Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda