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

168
Vistas
Can't Update state after fetch request

I'm trying to make an app where I fetch data from a Graphql API, and update state after fetching, but after the successful request I'm getting the data but I can't update state with that data. when I console log the response data it's showing the array with required data but when I update state and console log the state it's showing empty array.

I need to update the state to use it in the component, when i'm doing this it's throwing error that currList is undefined.

here are pictures of code and console.

export default function App() {
  const [search, setSeach] = useState("");
  const [currList, setCurrList] = useState([]);

  const fetchShips = async () => {
    const response = await request(gql`
      {
        ships {
          name
          home_port
          image
        }
      }
    `);
    console.log("request response", response.data);
    setCurrList(response.data);
    console.log("currlist:", currList);
  };

  useEffect(() => {
    fetchShips();
  }, [currList]);

  const Searchitems = (event) => {
    setSeach(event.target.value);
    setCurrList(
      currList.filter((item) => {
        return item.name.includes(search) || item.home_port.includes(search);
      })
    );
  };

  return (
    <div className="App">
      <div className="container">
        <header></header>
        <div className="body">
          <input
            type="text"
            id="search"
            value={search}
            onChange={Searchitems}
            className="input"
            placeholder="Search Ships"
          />
          <p>Total Count: {currList.length}</p>
          <div className="ships">
            {currList.map((item, index) => {
              return (
                <Ship
                  key={index}
                  name={item.name}
                  port={item.port}
                  img={item.image}
                />
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

the State is Updated just not when the code is running that's why it logs that the state is an empty array, try to console.log it once again and you will see that there is something in the List.

over 4 years ago · Santiago Trujillo Denunciar

0

That's normal, everything is happening asynchronously. React will trigger a re-render once your currList is updated and you will get its new value. If you want to listen to this change, you have to use useEffect with currList as a dependency.

useEffect(() => {
    console.log("List is updated", currList);
}, [currList]);
over 4 years ago · Santiago Trujillo Denunciar

0

The function fetchShips has closure over the currList state variable that blongs to specific render call, so when you log it after calling setCurrList it shows you the previous state not the updated state, you can log it in the useEffect to see the changes.

over 4 years ago · Santiago Trujillo 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