Palaniichuk Dmytro
Palaniichuk Dmytro

Reputation: 3173

Async/await call action from React component

I have a method lookupComplete in react component that call action checkIfAssign, I need wait to response and depend on this response trigger in this method another methods. But recieve Promise {<pending>} "result". How to wait until resolve this action ?

Component:

export class Test extends Component {
  ....

  lookupComplete = (tagId = this.state.tagId) => 
    this.setState({tagId}, () => {
      let result = this.props
        .checkIfAssign(this.state.tagId, this.props.accessToken)

    result.status 
      ? this.triggerTransition(transitions.ClickCheckTag) 
      : this.triggerTransition(transitions.Test)
    })
}

export const mapDispatchToProps = dispatch => ({
  checkIfAssign: (tagId, accessToken) => 
    dispatch(TagAssignmentActions.checkTagAssignment(tagId, accessToken)),
})

Action:

export const checkTagAssignment = (tagId, token) => async dispatch => {
  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
  })

  let status, assignee, response
  try {
    response = await DeviceApi.checkTagAssignment(tagId, token)

    assignee = response.result.assignee
    status = response.result.status
  } catch (e) {
    if (e && e.status === httpStatusCode.notFound)
      status = TagStatus.NotFound
  }

  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
    status,
    assignee,
    response,
  })
  console.log(response, 'response')
  return response
}

Upvotes: 0

Views: 2003

Answers (1)

Christopher Francisco
Christopher Francisco

Reputation: 16268

If you want to await, you should make your function async:

lookupComplete = async (tagId = this.state.tagId) => 
...

  let result = await this.props
    .checkIfAssign(this.state.tagId, this.props.accessToken)

However, this is a bad pattern. The correct one would reading the status from your app state. As you can see, your action will update the app state here:

dispatch({
  type: TagAssignmentActionTypes.TagAssignmentChanged,
  status,
  assignee,
  response,
})

If you're doing redux properly, your Test component is probably connect()ed to redux. In your mapStatesToProps you'd pass the value of status from the app state to the Test component props

const mapStateToProps = state => ({
  status: state.myNamespaceForTaskAssignment.status,
});

Then inside getDerivedStateFromProps(nextProps, prevState) you'd do the check for:

nextProps.status 
  ? this.triggerTransition(transitions.ClickCheckTag) 
  : this.triggerTransition(transitions.Test)

Or something like this.

Upvotes: 2

Related Questions