Jason
Jason

Reputation: 118

How to use redux-thunk correctly, with React?

I am trying to get my app not to complain that action does not have an undefined type property.

I have set up my client side render as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import routes from './shared/routes';
import rootReducer from './shared/reducers';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';

let initialState = window.__INITIAL_STATE_;

const store = createStore(rootReducer, initialState, applyMiddleware(thunk));

ReactDOM.render(
<Provider store={store}>
    {routes}
</Provider>, document.getElementById('app'));

Which I believed to be the correct way?

Upvotes: 1

Views: 772

Answers (1)

Franco Risso
Franco Risso

Reputation: 1582

Yes. In the redux-thunk github page there's a great example of how to use it.

For your actions, if it's an async action, I'm using this approach to dispatch an async action with promises:

Action:

export function add({name, time}) {
  return dispatch => {
    dispatch({type: ADD});
    return postJSON('/api/services', {
      name,
      time,
    })
    .then(service => {
      dispatch({
        type: ADD_SUCCESS,
        service: service,
      });
    })
    .catch(error => {
      dispatch({
        type: ADD_FAILURE,
        error,
      });
    });
  };
}

Inside my component:

  addService () {
    const { dispatch } = this.props;
      return (fields) => {
        dispatch(add(fields));
        dispatch(toggleAddForm());
      };
  }

Upvotes: 1

Related Questions