Keep getting 'dispatch' undefined with redux-promise

Question!

I am really new to Redux and its concepts, especially middleware so I do apologise for any stupid errors.

In this project of mine, I need to use redux-thunk. I've looked at a few guides and explanations on how to apply them. I then kept receiving an error "Uncaught TypeError: Cannot read property 'dispatch' of undefined". I opened developer tools and got shown this error:

enter image description here

I have no idea if I am doing anything right. Below are the codes for my action creators and store.

actions/index.js

import axios from 'axios';

export function fetchLessons() {
  console.log('called!');
  return function(dispatch) {
    axios.get(`${ROOT_URL}/lessons`)
      .then((response) => {
        dispatch(fetchLessonsSuccess(response))
      })
      .catch((err) => {
        dispatch(fetchLessonsError(err))
      })
  }
}

function fetchLessonsError(){
  return "An error has occured";
}

function fetchLessonsSuccess(response) {
  return {
    type: FETCH_LESSONS,
    payload: request
  };
}

index.js(store)

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import { Router, browserHistory } from 'react-router';
import rootReducer from './reducers/index';
import routes from './routes';
import promise from 'redux-promise';
import thunk from 'redux-thunk';

const middleware = applyMiddleware(promise(), thunk);
const store = createStore(rootReducer, compose(middleware));

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>
  , document.querySelector('.container'));
By : Adam Loh


Answers

i am not totally sure but something like this

export function fetchLessons() {
  console.log('called!');
  return function(dispatch) {
    return dispatch({
      type: 'FETCH_LESSONS',
      payload: axios.get(`${ROOT_URL}/lessons`)
        .then((response) => {
          dispatch(fetchLessonsSuccess(response))
        })
        .catch((err) => {
          dispatch(fetchLessonsError(err))
        });
    });
  };
}

function fetchLessonsError(){
  return "An error has occured";
}

function fetchLessonsSuccess(response) {
  return {
    type: 'FETCH_LESSONS_FULFILLED',
    payload: response
  };
}


I believe your call to applyMiddleware() is slightly off. You want to pass the imported promise middleware directly, not call it: applyMiddleware(promise, thunk).

That function is basically a factory. Redux will call it and pass in the store's dispatch function, which the middleware can then use to dispatch actions whenever it's ready.



The majority of your concerns seem to boil down to either misuse or misunderstanding.

  • much bigger codesize

    This is usually a result of properly respecting both the Single Responsibility Principle and the Interface Segregation Principle. Is it drastically bigger? I suspect not as large as you claim. However, what it is doing is most likely boiling down classes to specific functionality, rather than having "catch-all" classes that do anything and everything. In most cases this is a sign of healthy separation of concerns, not an issue.

  • ravioli-code instead of spaghetti-code

    Once again, this is most likely causing you to think in stacks instead of hard-to-see dependencies. I think this is a great benefit since it leads to proper abstraction and encapsulation.

  • slower performance Just use a fast container. My favorites are SimpleInjector and LightInject.

  • need to initialize all dependencies in constructor even if the method I want to call has only one dependency

    Once again, this is a sign that you are violating the Single Responsibility Principle. This is a good thing because it is forcing you to logically think through your architecture rather than adding willy-nilly.

  • harder to understand when no IDE is used some errors are pushed to run-time

    If you are STILL not using an IDE, shame on you. There's no good argument for it with modern machines. In addition, some containers (SimpleInjector) will validate on first run if you so choose. You can easily detect this with a simple unit test.

  • adding additional dependency (DI framework itself)

    You have to pick and choose your battles. If the cost of learning a new framework is less than the cost of maintaining spaghetti code (and I suspect it will be), then the cost is justified.

  • new staff have to learn DI first in order to work with it

    If we shy away from new patterns, we never grow. I think of this as an opportunity to enrich and grow your team, not a way to hurt them. In addition, the tradeoff is learning the spaghetti code which might be far more difficult than picking up an industry-wide pattern.

  • a lot of boilerplate code which is bad for creative people (for example copy instances from constructor to properties...)

    This is plain wrong. Mandatory dependencies should always be passed in via the constructor. Only optional dependencies should be set via properties, and that should only be done in very specific circumstances since oftentimes it is violating the Single Responsibility Principle.

  • We do not test the entire codebase, but only certain methods and use real database. So, should Dependency Injection be avoided when no mocking is required for testing?

    I think this might be the biggest misconception of all. Dependency Injection isn't JUST for making testing easier. It is so you can glance at the signature of a class constructor and IMMEDIATELY know what is required to make that class tick. This is impossible with static classes since classes can call both up and down the stack whenever they like without rhyme or reason. Your goal should be to add consistency, clarity, and distinction to your code. This is the single biggest reason to use DI and it is why I highly recommend you revisit it.

By : David L


This video can help you solving your question :)
By: admin