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

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

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 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