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

91
Visualizações
Store data from json to localStorage browser

I'm trying to make a program where you get from an API, and every 3 seconds you get a new value, so far so good, I get the value using useEffect/useState.

const [data, setData] = useState();
    useEffect(() =>{
        const interval = setInterval(() => {
          getData()
        },3000);
        return () => clearInterval(interval);
      },[])
      //fetch the data function
      const getJoke = (() => {
        fetch('API URL')
        .then((res) => res.json())
        .then((res) => {
          setData(res.value);
        })
        .catch((err) => console.log(err));
      })

So everything work fine with this, I get the data appear every 3 seconds

<button id="button" onClick = {handleGetT}>{isActive ? 'Get Data' : 'Stop'}</button>
        <h3>{isActive ? null : data}</h3>

But I'm really struggling to save the like as favourite. I have an other button where when you click it you save it on the localstorage browser data.

<button id="button" onClick = {localStorage.setItem("name",data)}>Save!</button>

I know the above may not be appropriate way of doing it, for some reason I get different data saved on localstorage every 3 seconds, and I would like to save the when clicked the joke that appears, on lets say an array, so I could use it later to print it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The function in onClick runs itself every time the button is rendered. You need to wrap it in an anonymous function like this:

<button id="button" onClick={()=>{localStorage.setItem("name",data)}}>Save!</button>

More info: https://stackoverflow.com/a/33846760/9224578

about 4 years ago · Juan Pablo Isaza 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