1

Can, in a react component, async be used outside componentDidMount()

I have something like this

  async componentDidMount() {
    this.props.functionA();
  }

const mapDispachToProps = dispatch => {
  return {
    functionA: () => dispatch(actionCreator.someStuff())
  };
};

export const someStuff= () => async (dispatch) => {
  try {
    const xyz= await callingsomepromise();
    ...

now if I call functionA someplace else of componentDidMount() it doesn't work. My question is, how can I call functionA in other parts, like after clicking a button for example.

OWADVL
  • 8,899
  • 6
  • 50
  • 66

1 Answers1

1

You can call it from an event handler e.g. onClick or any of the React component lifecycle hooks e.g. componentdidupdate. Or even in the constructor...

Simply:

class MyComp extends React.Component {
  constructor(props) {
    super(props)
    this.props.functionA();
  }
  componentDidMount() {
    ...
  }

  onClick() {
    this.props.functionA()
  }

  componentDidUpdate(prevProps) {
    if(somecondition) {
      this.props.functionA();
    }
  }

  render() {
    return <div onClick={this.onClick.bind(this)} />;
  }

}

You only need to use async/await if you need to wait for some async action e.g. Promise to resolve.

class MyComp extends React.Component {

  async onClick() {
    await this.props.functionA()
    doSomethingAfter()
  }

  render() {
    return <div onClick={this.onClick.bind(this)} />;
  }

}

EDIT - call a redux action like this:

import { actionName } from 'actions/myactions';

Then call it from within your component:

class MyComp extends React.Component {
  onClick() {
    this.props.functionA()
  }

  render() {
    return <div onClick={this.onClick.bind(this)} />;
  }
}

Then bind the function to your action and connect up to redux:

const mapDispatchToProps = dispatch => ({
  FunctionA: () => dispatch( actionName() )
});

Now connect your component to your mapped action and the redux store:

export default connect( mapStateToProps, mapDispatchToProps )( MyComp );
jsdeveloper
  • 3,416
  • 1
  • 11
  • 14
  • thanks for the answer, but it just doesn't work. the dispatch action is not called.... – OWADVL Mar 17 '19 at 12:27
  • . I'm trying to call this function -> https://github.com/AndreiD/my-react-dapp-template/blob/c7c2a88507e72c4776c81e7e5dd87b6439221187/src/components/Home.jsx#L16 on a button click – OWADVL Mar 17 '19 at 12:34
  • ok what is your exact error message? I can only assume that web3actions is not correctly exporting the function you want. – jsdeveloper Mar 17 '19 at 14:44
  • I got no error message, simply nothing is happening – OWADVL Mar 18 '19 at 11:05
  • you need to make sure that you've connected up the function you're trying to call to a redux action properly - Ill update – jsdeveloper Mar 18 '19 at 14:14