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
As you can see that API is returning value but setState() is not working.
What To Do?