Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!