1

This is my parent code:

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: [],
        };
    }
    componentDidMount() {
        this.getTags();
    }

    getTags() {
        //method gets tags from the backend
    }
    render() {
        return <Child tags={this.state.tags} />;
    }
}

And this is basically my child component:

export default class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: props.tags,
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            tags: nextProps.tags,
        });
    }
}

But when I console log tags somewhere in the Child component, it is undefined. Maybe it is undefined because the child component gets rendered before the parent component calls the method getTags? Or is there any other problem with this code? And how can I avoid this problem that tags are undefined in the child component?

Cheers

Adam Jeliński
  • 1,708
  • 1
  • 10
  • 21
Lennart
  • 67
  • 1
  • 10
  • _But when I console log tags somewhere in the Child component_. Where is "somewhere"? Could you put in your code in which place you are calling the `console.log`? – ElChiniNet May 03 '20 at 19:52

2 Answers2

2

To avoid your problem, you shouldn't be rendering your Child component until the this.state.tags has any useful values.

Here is how you can do it and also show a "Loading..." text, so the user isn't worried the page is broken.

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: [],
        };
    }
    componentDidMount() {
        this.getTags();
    }

    getTags() {
        //method gets tags from the backend
    }
    render() {
        return this.state.tags.length ? (
            'Loading...'
        ) : (
            <Child tags={this.state.tags} />
        );
    }
}
Adam Jeliński
  • 1,708
  • 1
  • 10
  • 21
0

Your child component will definitely get rendered with the empty 'tags' array as a prop. Then, when getTags() returns the data, the newly populated tags array will be passed to the child as a prop, forcing the child to get re-rendered with the new data.

It should be the empty array though, not "undefined". You might check your getTags() method and the API you are calling to make sure you aren't getting "undefined" from there.

componentWillReceiveProps is legacy and should not be used. See the following link in the React docs for details: https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

That documentation will walk you through what to do if you need to perform side effects as a result of changing props.

Right now the only thing is componentWillReceiveProps is to set local state to the props, which is totally superfluous. Is there something else you are needing to do there?

justin
  • 192
  • 1
  • 6