Search code examples
chakra-uireact-tsx

Why is React Not Rendering my Data from my api?


I'm using:

  1. React Typescript
  2. Chakra UI

I'm simply retrieving data from the api:

line20-line37

  • I use a useEffect to from from the api, and passing the response to a local array.
  • I then map through the array to give only the items I need.
  • I place this map within chakra components

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:

webpage-returned

can someone tell me why it's not rendering the {orders.productName}?


Solution

  • 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)
    }, [])