0

I have a component that triggers some methods that depend on async API request. I use componentWillmount to check some props. If this prop is true I trigger some function otherwise false. But the problem is, that first time the prop is undefined, only after some time it will become false or true. How to check it and wait until request resolved?

componentWillMount = () => {
  this.props.init(parseInt(this.props.tagId, 16), this.props.accessToken);
  if (!this.props.notFound && !this.props.person) this.props.onFreeTag();
};
Joshua
  • 3,055
  • 3
  • 22
  • 37
Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66

2 Answers2

1

Use componentWillReceiveProps lifecycle function, something like:

componentWillReceiveProps = (nextProps) => {
    if (!nextProps.notFound && !nextProps.person)
        nextProps.onFreeTag()
    }
}
StackedQ
  • 3,999
  • 1
  • 27
  • 41
1

It appears that first time when the component loads or get called your are passing it some value which is undefined initially and later becomes available. For example lets say you have a parent component as following

class Parent extends React.Component {
    constructor() {
        this.state = {0}
    }

    render() {
        <Child value={this.state.value} />
    }
}

As you can see, initially the state doesn't have a property value so the Child will receive undefined for this.props.value. It will only receive not undefined when some parent function changes it like this,

class Parent extends React.Component {
    constructor() {
        this.state = {0}
    }

    onAction() {
        this.setState({value: true})
    }

    render() {
        <Child value={this.state.value} />
    }
}

So if on some event parent calls its OnAction it will change the state and Child will get this.props.value as true but as Child will be already rendered componentWillMount hook will not get triggered but componentWillReceiveProps will. So if you want to use the prop in componentWillMount make sure its passed at the first render of the child and if that is not possible use componentWillReceiveProps to process the props

Umair Abid
  • 1,453
  • 2
  • 18
  • 35