简体   繁体   中英

How can i fetch the data of an get api call which is in the format as nested array of object in array of object in reactjs?

  1. Firstly this is my api data data.
{
    "code": 200,
    "message": "Request fulfilled, document follows",
    "data": [
        {
            "sn": "ACC-LEW-1JY1-J4X2",
            "created_on": "2022-11-12T07:42:26.531786Z",
            "owner": "devtest01",
            "toy_user_type": 1,
            "shared_status": "Owned",
            "product_data": {
                "id": 179,
                "product_skuid": "any-name",
                "variant_id": "any-id",
                "product_name": "any-product-name",
                "product_type_val": "car-toy",
                "product_category_slug": "stunt-car",
                "desc": null,
            },
            "attribute_data": {
                "toy_distance_travelled": "0",
                "toy_time_played": "0",
                "toy_last_updated": "0",
                "toy_donuts": "0",
                "toy_rash_drives": "0",
                "toy_smooth_drives": "0",
                "toy_top_boost": "0",
                "toy_tank_size": "0",
                "toy_draft_collector": "0",
                "toy_acceleration": "0",
                "toy_braking": "0",
                "toy_name": "",
                "toy_last_played": "",
                "toy_experience": "0",
                "toy_drifts": "0",
                "toy_top_speed": "0",
                "drifts": "0",
                "toy_last_maintainence_distance": "0"
            },
            "game_attribute_data": [
                {
                    "attr_key": "td_distance_travelled",
                    "value": 21,
                    "sync_version": 3
                },
                {
                    "attr_key": "td_time_played",
                    "value": 8,
                    "sync_version": 3
                },
                {
                    "attr_key": "td_drifts_completed",
                    "value": 3,
                    "sync_version": 3
                }
            ]
        },
    ],
    "error": null,
    "server_time": "2022-11-21T12:57:44.319Z"
}
  1. I want to access the data of game_attribute_data. I tam trying to use map function but I am unable to get the data.

  2. This is my api call using fetch method in React.js

const allToysData = async () => {
    await fetch(
      `URL`,
      {
        method: "GET",
        headers: {
          Authorization: "token"
        },
        redirect: "follow"
      }
    )
      .then(response => response.json())
      .then(data => {
        const toysdata = data.data;
        const updatedToysData = toysdata.map(
          (x: {
            created_on: any;
            owner: any;
            shared_status: any;
            sn: any;
            attribute_data: any;
            product_data: any;
            game_attribute_data: any;
          }) => ({
            created_on: x.created_on,
            owner: x.owner,
            shared_status: x.shared_status,
            sn: x.sn,
            toy_drifts: x.attribute_data.toy_drifts,
            toy_time_played: x.attribute_data.toy_time_played,
            toy_last_played: x.attribute_data.toy_last_played,
            toy_last_maintainence_distance: x.attribute_data.toy_last_maintainence_distance,
            product_skuid: x.product_data.product_skuid,
            product_image_1x: x.product_data.data.product_image_1x,
            game_attribute_data: x.game_attribute_data.map(x => x),
          })
        );

        const result = updatedToysData.map(x => x.game_attribute_data);
        setToyAttribute(updatedToysData);
        setArrToys(updatedToysData);
      })
      // eslint-disable-next-line no-console
      .catch(error => console.log(`Error: ${error}`));
  };

  1. I want to show the data of game_attribute_data in a table. How should I access the data in React.js.

I already tried to get the data using map function but the data is not rendering in table so Please show me where my mistake might be.

{
    data.data
    .map((item)=>item.game_attribute_data)
    .map((game_attribute_data)=>(game_attribute_data)
    .map((value,key)=>{

    return <tr key={key}>
      <td>{value.attr_key}</td>
      <td>{value.value}</td>
      <td>{value.sync_version}</td>
    </tr>
  }))
}

Here's the snippet. View it on fullpage

 // Get a hook function const {useState} = React; const Example = ({title}) => { const [data,setData] = useState({ "code": 200, "message": "Request fulfilled, document follows", "data": [ { "sn": "ACC-LEW-1JY1-J4X2", "created_on": "2022-11-12T07:42:26.531786Z", "owner": "devtest01", "toy_user_type": 1, "shared_status": "Owned", "product_data": { "id": 179, "product_skuid": "any-name", "variant_id": "any-id", "product_name": "any-product-name", "product_type_val": "car-toy", "product_category_slug": "stunt-car", "desc": null, }, "attribute_data": { "toy_distance_travelled": "0", "toy_time_played": "0", "toy_last_updated": "0", "toy_donuts": "0", "toy_rash_drives": "0", "toy_smooth_drives": "0", "toy_top_boost": "0", "toy_tank_size": "0", "toy_draft_collector": "0", "toy_acceleration": "0", "toy_braking": "0", "toy_name": "", "toy_last_played": "", "toy_experience": "0", "toy_drifts": "0", "toy_top_speed": "0", "drifts": "0", "toy_last_maintainence_distance": "0" }, "game_attribute_data": [ { "attr_key": "td_distance_travelled", "value": 21, "sync_version": 3 }, { "attr_key": "td_time_played", "value": 8, "sync_version": 3 }, { "attr_key": "td_drifts_completed", "value": 3, "sync_version": 3 } ] }, ], "error": null, "server_time": "2022-11-21T12:57:44.319Z" }) return ( <table > <thead> <tr> <th>Attr Key</th> <th>Value</th> <th>Sync Version</th> </tr> </thead> <tbody> { data.data.map((item)=>item.game_attribute_data).map((game_attribute_data)=>(game_attribute_data).map((value,key)=>{ console.log(value) return <tr key={key}> <td>{value.attr_key}</td> <td>{value.value}</td> <td>{value.sync_version}</td> </tr> })) } </tbody> </table> ); }; // Render it ReactDOM.createRoot( document.getElementById("root") ).render( <Example title="Example using Hooks:" /> );
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

According to your latest comment above, you're only looking for help getting & storing game_attribute_data separate from the rest of the API response, correct? If so, here's what I'd recommend:

  1. Create a new state variable to store this data. Ex:
const [gameAttribData, setGameAttribData] = useState([]);
  1. In your allToysData function, instead of mapping through the API response data, I would probably create a few variables (one for each unique state variable you're going to end up setting), loop through the response data (using .forEach ), and update each variable for each element you look at. Example for game_attribute_data :
.then(data => {
  const newGameAttribData = [];

  // Loop through API response data
  data.data.forEach((x: {
    created_on: any;
    owner: any;
    shared_status: any;
    sn: any;
    attribute_data: any;
    product_data: any;
    game_attribute_data: any;
  }) => {
    // Add this element's data to arrays
    newGameAttribData.push(x.game_attribute_data);
  });

  // Update your state variables
  setGameAttribData(newGameAttribData);
});

Now you should be able to access gameAttribData outside of this function so you can render it to the screen. Hopefully you can adapt the above code for your use (I'm not sure exactly how you're wanting to render it to the screen).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM