Search code examples
reactjsaxiosreact-hooksuse-effectuse-state

In ReactJS, facing problem in rendering the data from an API due to its odd structure


This is my code:

import React, { useState, useEffect } from "react";
import axios from 'axios';

function App() {

  const [arrName, setName] = useState();

  useEffect(() => {
    
    axios.get('URL')
        .then( response => {
          // console.log( response.data )
          setName( response.data )
        });
    
  }, [])

  const foo = () => {
    console.log(arrName.data[0].data[0]._id)
    // following two console statements need not to be in the code. I am putting them only to show the structure of API

    console.log(arrName)
    console.log(arrName.data)
  }

  return(
    <div> 
      Hi,  I'm the component 
      <button onClick={foo}> console </button>    
    </div>
  ) 
}

export default App;

Console response screenshot

Console response screenshot

I want to simplify the following statement. So that I can easily iterate the API and print anything from the API. However, I am printing only an id here.

console.log(arrName.data[0].data[0]._id)

Following command breaks the code

<div>  
       arrName.data[0].data.map((item) => <li>{item._id}</li> ) }
 </div>

Kindly, Help me what changes should I make to my code.


Solution

  • Based on the replied comment, you would do it like so:

    arrName?.data &&
      arrName.data.map((item) => (
        <ul>
          {item.data.map((chidlItem) => (
            <li> {chidlItem._id} </li>
          ))}
        </ul>
      ));
    

    The ? is Optional Chaining which is to check if the reference in the chain is valid, so it will skip the map function if arrName or arrName.data is null/undefined