Search code examples
reactjsdatabasejsxnested-loops

Display data from database via ID from nested array


I am trying to get data (balance and employee name) to show to the user. I have a nested array, with multiple objects that hold basic employee information. The id I need to access is in the nested objects - see below data structure example from Mongo DB.

The problem I am facing, the only ID I can access is the first id, I have done some research and mongo only displays from the highest ID. How can I access the nested IDs to display the data I need? Is it even possible? I have tried to map in the Axios request as shown in the code, nothing works.

{
    "message": "Post found",
    "data": {
        "company": "HIJ",
        "_id": "60fb75123ca85f76447d2b58",
        "details": [
            {
                "employee": "aa",
                "date": "aa",
                "tax": "aa",
                "balance": "3",
                "fee": 11,
                "notes": "aa",
                "_id": "60fb75123ca85f76447d2b59"
            },
            {
                "employee": "bb",
                "date": "bb",
                "tax": "bb",
                "balance": "3",
                "fee": 12,
                "notes": "bb",
                "_id": "60fb75123ca85f76447d2b5a"
            }
        ],
        "__v": 0
    }
}
    

here is the code:

import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";

const Success = () => {
  const [company, setCompany] = useState("")
  const [balance, setBalance] = useState("");
  const [employee, setEmployee] = useState("");
  const { id } = useParams();

  useEffect(() => {
    axios
      .get(`http://localhost:5000/get-snapshot-id-test/${id}`)
      .then((res) => {
        console.log("res", res.data.data);
        setBalance(res.data.data.map((b) => b.details.map((innerary) => innerary.balance)));
        setEmployee(res.data.data.map((e) => e.details.map((innerary) => innerary.employee)));
      })
      .catch((err) => {
        console.log(err);
      });
  }, [setBalance, setEmployee, id]);


  return (    
     { balance === "0.00" && <h4>{employee} is paid in full.</h4> }
     { balance !== "0.00" && <h4>{employee} new balance: ${balance}.</h4>}
  );
};
export default Success;

Solution

  • the answer was to fix the map in the Axios request. Drew Reese lead me in the right direction pointing out the res.data.data.details. Then I needed to take that result and point to the desired state

     useEffect(() => {
    axios
      .get(`http://localhost:5000/get-snapshot-id-test/${id}`)
      .then((res) => {
        console.log("RESPONCE", res.data.data.details);
        setBalance(res.data.data.details.map((r) => r.balance));
        setEmployee(res.data.data.details.map((r) => r.employee));
      })
      .catch((err) => {
        console.log(err);
      });
      }, [setBalance, setEmployee, setNotes, id]);