Home > Software engineering >  State not being updated after axios request
State not being updated after axios request

Time:08-01

I previously had this code that made a get request via Axios to my local host to fetch data from an API.

export default function BasicTable() {
  const [orders, getOrders] = useState(null);
  useEffect(() => {
     fetchOrders();
  }, []);
  const fetchOrders = () => {
  axios.get("http://localhost:3000/orders").then((response) => {
      const res_orders = response.data.Items;
      console.log(res_orders);
      getOrders(res_orders);
  })
  .catch(error => console.error(`Error: ${error}`));

  }
  return (

      <div className="Table">
      <h3>Recent Orders</h3>  
        <TableContainer
          component={Paper}
          style={{ boxShadow: "0px 13px 20px 0px #80808029" }}
        >
          <Table sx={{ minWidth: 650 }} aria-label="simple table">
            <TableHead>
              <TableRow>
                <TableCell>Product</TableCell>
                <TableCell align="left">Tracking ID</TableCell>
                <TableCell align="left">Date</TableCell>
                <TableCell align="left">Customer</TableCell>
                <TableCell align="left">Company</TableCell>
                <TableCell align="left">Status</TableCell>
                <TableCell align="left">Quantity</TableCell>
                <TableCell align="left"></TableCell>
              </TableRow>
            </TableHead>
            <TableBody style={{ color: "white" }}>
            {orders && orders.map(order => (
              Object.keys(order.sales).map(sale => 
                <TableRow
                key={order.id}
               // sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
              >
                <TableCell component="th" scope="row">
                  {order.sales[sale].name}
                </TableCell>
                <TableCell align="left">{order.sales[sale].trackingid}</TableCell>
                <TableCell align="left">{order.orderplaced}</TableCell>
                <TableCell align="left">{order.name}</TableCell>
                <TableCell align="left">{order.company}</TableCell>
                <TableCell align="left">
                  <span className="status" style={makeStyle(order.sales[sale].status)}>{order.sales[sale].status}</span>
                </TableCell>
                <TableCell align="left">{order.sales[sale].sales}</TableCell>
                <TableCell align="left" className="Details">Details</TableCell>
              </TableRow>
              )))} 
         
            </TableBody>
          </Table>
        </TableContainer>
      </div>
  );
}

I changed the URL to my ec2 instance that was running the backend API I created. However, after changing it back to the localhost URL that I have running on a different port in my machine, I noticed that my orders state is undefined. It seems to be able retrieve the orders on the get request as I am able to print it out, but for some reason it seems as though the state never updates and thus my component does not render.

console output

I've tried changing my fetch orders to an async function but still, the same result happened.

CodePudding user response:

You should use this code instead of your code. Set orders as blank array in initial state and later set orders using the prevState syntax like as I did.

const [orders, getOrders] = useState([]);
  useEffect(() => {
     fetchOrders();
  }, []);
  const fetchOrders = () => {
  axios.get("http://localhost:3000/orders").then((response) => {
      const res_orders = response.data.Items;
      console.log(res_orders);
      getOrders(prevState => (res_orders));
  })
  .catch(error => console.error(`Error: ${error}`));

}

CodePudding user response:

I think this good approach for API calls...

const fetchOrders =async () => {
     let response=await axios.get("http://localhost:3000/orders");
          getOrders(response.data.Items);
      }
  • Related