Leonardo Marques
Leonardo Marques

Reputation: 93

How can i pass Actions info to Component, React + Redux?

So i'm doing a API request on my Action.js and when it's done, send a 'success' parameter to the component which it's calling the action.

What it's the best way to do that?

My code:

Action.js


export const setarLojas = (lojas) =>{
    return {
      type: SETAR_LOJAS,
      data: lojas
    }
  }

  export const carregarLojas = () => {
    return (dispatch) => {
      return API.get('loja')
      .then(response => {
        dispatch(setarLojas(response.data))

        // Example
        // return "success"
      })
      .catch(error => {
        throw(error);
      })
    }
  }

Component.js

componentDidMount(){
      this.props.carregarLojas();

      // Example
      // if(this.props.carregarLojas == "success") { alert("success") }
    }

Upvotes: 2

Views: 68

Answers (2)

Hsaido
Hsaido

Reputation: 125

You can use a status (as state in your reducer, in addition to your data) related to your action;

setarLojas: {
      data: actionData, 
      status: actionStatus
}

Then change the value of your status according to your action's result,

example values to use for the status state : 'request' | 'error' | 'timeout' | 'success'.

example action:

export const setarLojas = (lojas, status) =>{
   return {
      type: SETAR_LOJAS,
      data: lojas,
      status: status
   }
 }

export const carregarLojas = () => {
    return (dispatch) => {
      dispatch(setarLojas({}, 'request'));
      return API.get('loja')
      .then(response => {
        dispatch(setarLojas(response.data, 'success'));
      })
      .catch(error => {
         dispatch(setarLojas({}, 'error'));
         throw(error);
      })
    }
  }

In your components, after connecting it to the redux using the connect hoc, you can get your data like:

const mapStateToProps = state => ({
     setarLojasData: state.YOUR_REDUCER.getIn(['setarLojasData', 'data']), 
     setarLojasStatus: state.YOUR_REDUCER.getIn(['setarLojasData', 'status'])
})

There you go, you have now the status that describe your action's result and according to its value, you can manage your view then use the data.

Upvotes: 2

Sangam Rajpara
Sangam Rajpara

Reputation: 678

You should use Redux middleware Thunk to solve async api call issue. Thunk will handle your async api call.

Upvotes: 0

Related Questions