Profer
Profer

Reputation: 643

How to fire an action event in react 16.8?

I just came in react after an year and before that I used to use componentWillRecieveProps() to call api(fire an action) just after getting updated props.

  componentWillRecieveProps(nextProps) {
    if (nextProps.user !== this.props.user) {
      //Some api call using user prop
    }
  }

But now componentWillRecieveProps is replaced by getDerivedStateFromProps and there I cannot use this inside it. So how can I dispatch an event in newer react version or what is the best way?

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.user !== prevState.user) {
      this.fetchSetting();
      return { user: nextProps.user };
    }
    return null;
  }

  fetchSetting = async () => {
    const { fetchSetting } = this.props;
    const data = await fetchSetting();
  };

Upvotes: 0

Views: 105

Answers (2)

Rafael Rocha
Rafael Rocha

Reputation: 518

There are two ways you can achieve this: you can use the new useEffect hook or you can use componentDidUpdate to compare the props manually and call a method that updates the state based on that.

The preferred way by the React team is the functional way (yea I know it's weird) using this: https://reactjs.org/docs/hooks-effect.html

If you want to keep using the class-based way then you can use componentDidUpdate: https://reactjs.org/docs/react-component.html#componentdidupdate

Upvotes: 1

Merlin
Merlin

Reputation: 313

You can use the method componentDidUpdate(prevProps, prevState) which is a good replacement for componentWillReceiveProps().

Check the documentation here : componentDidUpdate (React.Component)

In you exemple you can do this :

static componentDidUpdate(prevProps, prevState) {
    if (this.props.user !== prevProps.user) {
        this.fetchSetting();
        return { user: this.props.user };
    }
    return null;
}

But actually, if you really want to match the latest recommendations of React you shouldn't use classes but hooks which is aimed to be the new replacement. You can find more information about hooks on the page : Introducing Hooks

Upvotes: 1

Related Questions