5

I'm new to react and I am trying to fetch data from an API and pass the data to a child component. I've passed the data to the state on my parent component, however, when I pass it to the child component as props it logs as an empty array. I'm sure there is something simple I am overlooking but I don't know what, my code is below

PARENT COMPONENT

import React, {Component} from 'react';
import Child from '../src/child';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
          properties: []
        }
    }

    getData = () => {
        fetch('url')
        .then(response => {
            return response.text()
        })
        .then(xml => {
            return new DOMParser().parseFromString(xml, "application/xml")
        })
        .then(data => {
            const propList = data.getElementsByTagName("propertyname");
            const latitude = data.getElementsByTagName("latitude");
            const longitude = data.getElementsByTagName("longitude");

            var allProps = [];

            for (let i=0; i<propList.length; i++) { 
                allProps.push({
                    name: propList[i].textContent,
                    lat: parseFloat(latitude[i].textContent), 
                    lng: parseFloat(longitude[i].textContent)
                });
            }

            this.setState({properties: allProps});
        });
    }

    componentDidMount = () => this.getData();

    render () {
        return (
            <div>
                <Child data={this.state.properties} />
            </div>
        )
    }
}

export default App;

CHILD COMPONENT

import React, {Component} from 'react';

class Child extends Component {
    initChild = () => {
        console.log(this.props.data); // returns empty array

        const properties = this.props.data.map(property => [property.name, property.lat, property.lng]);
    }

    componentDidMount = () => this.initChild();

    render () {
        return (
            <div>Test</div>
        )
    }
}

export default Child;
Sai
  • 801
  • 3
  • 10
  • 27

2 Answers2

4

Change the componentDidMount in the child to componentDidUpdate.

The componentDidMount lifecycle method is called only once in the starting. Whereas, the componentDidUpdate lifecycle method gets called whenever there is a change in the state of the application. Since api calls are asynchronous, the initChild() function is already called once before the api call's results are passed to the child.

Sharath Kumar
  • 300
  • 1
  • 3
  • 10
  • Thanks! that did the trick, so whenever a function in a child component requires data asynchronously from another component you call it with componentDidUpdate? – Sai Jul 05 '19 at 13:27
  • 1
    Depends on how you'll be using the props. But in this case, yes. – Sharath Kumar Jul 05 '19 at 13:51
0

You can use conditional rendering

import React, {Component} from 'react';

class Child extends Component {
    initChild = () => {
        if(this.props.data){
          const properties = this.props.data.map(property => [property.name, property.lat, property.lng]);
        }        
    }

    componentDidMount = () => this.initChild();

    render () {
        return (
            <div>Test</div>
        )
    }
}

export default Child;
illuminate
  • 81
  • 5