Pingo
Pingo

Reputation: 533

how to use asyn actions in redux

I want to know when my action has finished the request so I can treat data ( Kind of a promise ).

I'm using thunk to dispatch function.

Here is my action

export function addUser(nom,url) {
    return (dispatch) =>{

        axios.post('/', {
            nom: nom,
            url: url
        })
            .then(function (response) {
                dispatch(()=>{//somthing for the reducer})
                console.log(response);

            })
}

and in my component I want to perform something like this

addUser('test','test')
.then() // do something after the addUser is executed

Upvotes: 1

Views: 62

Answers (1)

Yakov Kiszner
Yakov Kiszner

Reputation: 99

The way we do this is in redux is by dispatching an action on success like this:

const addUserSuccess = () => {
  return {
    type: 'ADD_USER_SUCCESS',
  }
}


export function addUser(nom,url) {
  return (dispatch) =>{

    axios.post('/', {
       nom: nom,
       url: url
    })
    .then(function (response) {
       dispatch(addUserSuccess());
       console.log(response);
     })
}

Now in your reducer to something like this:

const initialState = { addedUser: false };

export default (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_USER_SUCCESS:
            return {
                ...state,
                addedUser: true
            };
        default:
            return state;
    }
}

Last but not least, connect your component to the store.

class ExampleComponent extends React.Component {
  componentDidMount() {
    addUser();
  }

  render() {
    if (props.addedUser) {
      // do something after the addUser is executed
    }

    return <div>Example</div>;
  }
}

const mapStateToProps = (state) => ({
    addedUser: state.user.addedUser
});
// connect is a react-redux HOC
const ConnectedComponent = connect(mapStateToProps)(ExampleComponent);

I know this is a lot of boilerplate but this is just a very basic overview. Find out more at Async Actions in the redux docs.

Update: If you what to work with the promise instead, you could do the following:

export function addUser(nom, url) {
  return (dispatch) =>{

    return axios.post('/', {
       nom: nom,
       url: url
    })
    .then(function (response) {
       dispatch(addUserSuccess());
       console.log(response);
     })
}

Then you could use it in the component.

addUser()().then();

Just make sure to call it twice, because addUser() is a function that returns a function that returns a promise

Upvotes: 1

Related Questions