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

264
Visualizações
How to fetch and manipulate data right when component mounts?

im having a little issue trying to fetch and filter some data when a component mounts. Basically what I am trying to do is to fetch some random data and then filter it with a condition. but the filtering of the data is not working, there is most likely a part I misunderstood using useEffect. I made a code sample where I simplified and replicated the issue on https://codesandbox.io/s/green-night-rhg4lj?file=/src/App.js

When I press on the button I expect the filtered data to be console logged, but gives me only an empty array, Ive tried to add "filteredData" or "fetchedData" as a dependency of the useEffect, and yes, it does help me getting the filtered data right at the start but goes into an endless loop because of the behaviour of the useEffect dependencies with obj and arrays. Anyone knows of a way to get the data from API/Database and filter it right on the mount without going into a fetch loop?

Here is also the code written beside the codesandbox:

import axios from "axios";
import { useState, useEffect, useCallback } from "react";

export default function App() {
  const [fetchedData, setFetchedData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);

  const getData = useCallback(async () => {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
    setFetchedData(data);
  }, []);

  useEffect(() => {
    getData();
    (async () => {
      await setFilteredData(fetchedData.filter((p) => p.title.length > 20));
    })();
  }, []);

  const clickHandler = () => {
    console.log(filteredData);
  };

  return (
    <div className="App">
      <button onClick={clickHandler}>Click</button>
    </div>
  );
}

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You almost right!
You were right when putting the request in the useEffect hook.

...
    const getData = useCallback(async () => {
        const { data } = await axios.get("https://jsonplaceholder.typicode.com/posts");

        return data
    }, []);

    useEffect(async () => {
        const dataFromAPI = await getData();
        setFilteredData(dataFromAPI.filter((p) => p.title.length > 20));
    }, []);
...

Instead updating the state in the getData funtion just return it.
In the useEffect you get that data and the do what ever you want to do there.

note: According to this it's ok to use async in useEffect

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