I'm using:
I'm simply retrieving data from the api:
See code here:
import React, { useEffect } from "react";
import { Box, Text } from "@chakra-ui/react";
import { useParams } from "react-router-dom";
import Header from "./BuyerHeader";
import instance from "../api/api";
import Orders from "../models/Orders.type";
function EditOrder() {
const { id } = useParams();
const userOrders: Orders[] = [];
useEffect(() => {
const controller = new AbortController();
let dataFetched = false;
async function getOrderById() {
if (!dataFetched) {
const response = await instance.get(`/api/v1/orders/${id}`);
console.log(response);
// setOrders(response.data.orders);
userOrders.push(response.data.orders);
}
}
getOrderById();
return () => {
dataFetched = true;
controller.abort();
};
}, []);
return (
<Box>
<Header />
<Box>Edit Order Page</Box>
<Box bgColor="pink" w={100} h={100}>
{/* <Text>{orders.productName}</Text> */}
<Text color="black" fontSize={20} fontWeight="bold">
Orders:
</Text>
{userOrders.map((orders) => (
<Text bgColor="black" fontSize={30} fontWeight="bold">
Item Name: {orders.productName}
</Text>
))}
</Box>
</Box>
);
}
export default EditOrder;
This is the response in console:
console-in-browser/response-from-api
so it is returning the correct data I want from the api
but this is what is rendering:
can someone tell me why it's not rendering the {orders.productName}?
You need to use useState instead of a const array. Using useState causes the component to re-render on state change.
So you use it like this:
const [userOrders, setUserOrders] = useState<Orders[]>([])
useEffect(()=>{
instance.get(`/api/v1/orders/${id}`).then((res)=> setUserOrders(res.data.orders))
(more code here)
}, [])