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

175
Vistas
setState() is not working inside useEffect();

I fetched some data from my Mongo database which is returned as an object inside my useEffect hook function i.e.response in my code. I then declare a state myorders and wanted to set its value coming from the API.And finally. I wanted to map these data into different rows in my UI.

But the problem is when I try to setState in the component by passing the fetched orders in the setState() function, it returns an empty object. The console.log(state) shows an empty array.

code

import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";

const Orders = () => {
  const router = useRouter();
  const [myorders, setMyorders] = useState();

  useEffect(() => {
    const fectOrders = async () => {

        let a = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/myorders`, {
          method: "POST", // or 'PUT'
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ token: localStorage.getItem("token") }),
        });
        let response = await a.json();
        console.log("RES = ",response)
        setMyorders(response.myorders)
        console.log("MY = ",myorders)
      }

      if (!localStorage.getItem("token")) {
        router.push("/");
      } else {
        fectOrders();
      }
  }, []);

  

  return (
    <div className="container mx-auto">
      <h1 className="font-bold text-center text-2xl p-8">My Orders</h1>
      <div className="flex flex-col">
        <div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
          <div className="py-2 inline-block min-w-full sm:px-6 lg:px-8">
            <div className="overflow-hidden">
              <table className="min-w-full border-[1px]">
                .
                .
                .
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};



export default Orders;

ANd I got these values

err

As you can see that API is returning value but setState() is not working.

What To Do?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I had add myorders as dependency in useEffect which solves the problem,

So my useEffect is like this

  useEffect(() => {
    const fectOrders = async () => {

        let a = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/myorders`, {
          method: "POST", // or 'PUT'
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ token: localStorage.getItem("token") }),
        });
        let response = await a.json();
        console.log("RES = ",response)
        //setMyorders(response.myorders)
        console.log("MY = ",myorders)
        return response.myorders;
      }

      if (!localStorage.getItem("token")) {
        router.push("/");
      } else {
        fectOrders().then((ord)=>setMyorders(ord)).catch((err)=>console.log(err));
      }
  }, [myorders]);
about 4 years ago · Juan Pablo Isaza 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