0

I'm trying to map through an Array of Objects, every object is fetched from a folder of JSONs in my project. then i want to Render each object as a react component. to achieve this i set the state of my component to that array of object.

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

when i console.log() my state it seems to be what i needed, but when i try to console.log() the first element of that array it is undefined. this is the console.log(this.state.data)

[]
0: {description: "AirEuropa Boarding Pass", organizationName: "Air Europa", passTypeIdentifier: "pass.com.globalia.aireuropa.boardingpass", serialNumber: "RB47ZP20082C640001010191641560895200000", teamIdentifier: "ELASV6M68G", …}
1: {formatVersion: 1, passTypeIdentifier: "pass.com.renfe-RenfeTicket", serialNumber: "00HHGV7F7353900982276", teamIdentifier: "H9VY2F2XZA", webServiceURL: "https://www.myserver.com/pathto/service", …}
length: 2
__proto__: Array(0)

why is this.state.data[0] undefined?

This is how i get data from JSONs

    const arr = [];
    axios
      .get("data")
      .then(res => {
        const arrayDatas = res.data;
        arrayDatas.forEach(element => {
          if (element.includes(".json")) {
            axios.get("data/" + element).then(res => {
              arr.push(res.data);
            });
          }
        });
        this.setState({
          data: arr
        });
      })
      .catch(error => console.error(error));
  }
Syertim
  • 147
  • 1
  • 12
  • 2
    Set the state in `.then(res => ...)` -> [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Andreas Nov 28 '19 at 11:57
  • the arr will be empty as the data is pushed after doing the api call – Madhu Nov 28 '19 at 12:08

2 Answers2

0

You should update your state as suggested below.

    const arr = [];
    axios
      .get("data")
      .then(res => {
        const arrayDatas = res.data;
        arrayDatas.forEach(element => {
          if (element.includes(".json")) {
            axios.get("data/" + element).then(res => {
              arr.push(res.data);
            });
          }
        });
        this.setState({
           data: arr
         });

      })
      .catch(error => console.error(error));
  }
Mukul Kumar Jha
  • 1,062
  • 7
  • 19
0
const arr = [];
    axios
      .get("data")
      .then(res => {
        const arrayDatas = res.data;
        arrayDatas.forEach(element => {
          if (element.includes(".json")) {
            axios.get("data/" + element).then(res => {
              this.setState({data: res.data});
            });
          }
      })
      .catch(error => console.error(error));
  }
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29