reduxjs / redux-thunk

Thunk middleware for Redux
MIT License
17.76k stars 1.05k forks source link

middleware is not a function #35

Closed johnjelinek closed 8 years ago

johnjelinek commented 8 years ago

I can't tell if this is a redux-thunk or a redux issue.

I have a store like this:

const store = compose(
    applyMiddleware(
        thunk,
        logger
    )
)(createStore)(counter);

This results in an error message:

./node_modules/redux/lib/utils/applyMiddleware.js:50
        return middleware(middlewareAPI);
               ^

TypeError: middleware is not a function
    at ./node_modules/redux/lib/utils/applyMiddleware.js:50:16
    at Array.map (native)
    at ./node_modules/redux/lib/utils/applyMiddleware.js:49:27
    at Object.<anonymous> (./index.js:63:105)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:136:18)

If I comment out thunk above, it continues:

const store = compose(
    applyMiddleware(
        // thunk,
        logger
    )
)(createStore)(counter);

store.dispatch({ type: INCREMENT });
store.dispatch({ type: INCREMENT });
store.dispatch({ type: DECREMENT });
$ node --harmony_default_parameters --harmony_destructuring index.js
will dispatch { type: 'INCREMENT' }
state after dispatch 1
will dispatch { type: 'INCREMENT' }
state after dispatch 2
will dispatch { type: 'DECREMENT' }
state after dispatch 1
johnjelinek commented 8 years ago

for reference, logger is defined as follows:

function logger({ getState }) {
    "use strict";
    return (next) => (action) => {
        console.log("will dispatch", action);
        let returnValue = next(action);
        console.log("state after dispatch", getState());
        return returnValue;
    };
}
johnjelinek commented 8 years ago

hrmm ... very strange -- when I console.log(thunk) I get undefined. I'm importing it with import thunk from "redux-thunk";

johnjelinek commented 8 years ago

If I do import * as thunk from "redux-thunk"; I can console.log(thunk) and get: [Function: thunkMiddleware]. However, if I console.log(thunk.default), I get undefined.

johnjelinek commented 8 years ago

ah ha - https://github.com/Microsoft/TypeScript/issues/2242#issuecomment-92218146. Note: if you're using typescript instead of babel as your transpiler, you have to use import thunkMiddleware = require("redux-thunk"); to get the default module.

johnjelinek commented 8 years ago

Also note: if you use the require above, tsc barfs about the transpile, but it does indeed execute:

Argument of type 'typeof "redux-thunk"' is not assignable to parameter of type 'Middleware'.
  Property 'name' is missing in type 'typeof "redux-thunk"'.
johnjelinek commented 8 years ago

Did I mention? This would be a great thing to add to the repo: https://github.com/gaearon/redux-thunk/issues/31#issuecomment-160767329. Maybe I'll add a PR.

johnjelinek commented 8 years ago

more reference on this here: https://angularclass.com/the-state-of-typescript-packages/

attsion commented 8 years ago

use “import thunk from "redux-thunk";” not “import {thunk} from "redux-thunk";”

sbabeal commented 8 years ago

That still doesn't fix the typing issues. To use the import thunk syntax thunk should be exported as default. If I change the export statement in the typing file to export defaut and get rid of the equal size, it works. This is the same approach that redux-logger took.

image

sbabeal commented 8 years ago

I just looked at the PR and it was already in this format. While my typescript compiler 1.7.6 seems to accept either version, web storm 11 complains that thunk is not exported default. And my understanding was that you couldn't use the import default syntax without declaring an default export. Here is the info from the TypeScript specification. So I do not understand why it was changed. The only thing i can tell from this an the other issue is that web pack couldn't properly load the file based on the import statement which sounds like a webpack issue. Could someone either correct my understanding of the TypeScript spec or reopen this issue?

image

image

image

gaearon commented 8 years ago

Redux Thunk currently uses CommonJS. It does not explicitly export a “default”. We should probably start using ES modules internally and export a CommonJS compat build with default as the exported key, as well as an ES modules build, but this can only be done after bumping a version because it breaks backwards compat.

born2net commented 8 years ago

any fix for this as I still can't use Redux with systemjs, have to use commonjs with ng2 becuase of this as this works fine in commonjs:

import * as thunkMiddleware from 'redux-thunk';

but will fail with system. tried

use “import thunk from "redux-thunk";”

but no luck (yes using TypeScript as well)

regards

Sean

born2net commented 8 years ago

@johnjelinek I can't use require as I am trying to switch to systemjs from cjs so this wont work

import thunkMiddleware = require("redux-thunk")

any other workaround?

regards

born2net commented 8 years ago

@gaearon any idea when the fix of exporting default be put in place as this is preventing us from moving to system from cjs

gaearon commented 8 years ago

@born2net

I don’t understand what you’re trying to do. You can either

import thunk from 'redux-thunk'

in an ES modules environment, or

var thunk = require('redux-thunk').default

in a CommonJS environment.

Why aren’t these cases working for you?

gaearon commented 8 years ago

Also make sure you’re using 2.x.

gaearon commented 8 years ago

https://github.com/gaearon/redux-thunk#note-on-2x-update

born2net commented 8 years ago

TX, you got it, I was one version behind... 2.x fixed it!!!!!

gaearon commented 8 years ago

Glad to hear it! Cheers.

zourtney commented 8 years ago

Here another permutation for anyone using commonjs modules with Typescript. Works for me... YMMV.

typings install redux-thunk --save

Then:

import * as thunk from 'redux-thunk';

redux.createStore(rootReducer, applyMiddleware(
  thunk.default   // <-- the aforementioned `.default`
));
Truedrog commented 8 years ago

@zourtney i tried this also, but i cant do this

import {loadCourses} from './actions/courseActions';
store.dispatch(loadCourses());
export function loadCourses() {
  return function name(dispatch) {
    return courseApi.getAllCourses()
      .then(courses => {
        dispatch(loadCoursesSuccess(courses));
      })
      .catch(error => {
        throw (error);
      });
  };
}

[ts] Argument of type '(dispatch: any) => Promise' is not assignable to parameter of type 'Action'. Property 'type' is missing in type '(dispatch: any) => Promise'. (alias) loadCourses(): (dispatch: any) => Promise

zourtney commented 8 years ago

@Truedrog, I tried for a while but can't reproduce that. I can't tell if it's a problem with the code, or just incorrect typings...

At any rate, I don't think it's related to import / middleware hookup.

mattdell commented 8 years ago

I've followed this thread but I can't seem to resolve my issue.

I'm getting the middleware is not a function console error after upgrading to Babel 6. My original code used the ES6 import

import thunk from 'redux-thunk'

And I've tried the ES5 + default

const thunk = require('redux-thunk').default;

I was on redux-thunk v1 but have upgraded to v2.1.0 and redux v3.5.2.

I'm stumped...

EDIT:

Facepalm. It wasn't thunk afterall, but logger where I am using ES5 require.

const logger = require('../middleware/logger')

becomes

const logger = require('../middleware/logger').default;

Hope this helps someone else. 👍

mrandri19 commented 8 years ago

It's provably too late but with typescript tsc and the dt~redux-thunk typings I could fix it by doing: import { default as thunk } from "redux-thunk"; and then createStore(reducer, applyMiddleware(thunk));

savovsky commented 7 years ago

After facing recently same issue and none of the above worked for me I've tried with importing just {createLogger} that sorted the issue when new logger instance was passed to applyMiddleware.

import { applyMiddleware, createStore } from 'redux';
import promise from "redux-promise-middleware";
import thunk from "redux-thunk"
import { createLogger } from "redux-logger";

import reducer from "./reducers";
const middleware = applyMiddleware(  promise(),  thunk,  createLogger() );
export default createStore(reducer, middleware);

Works under Typescript and Babel because in my attempts to isolate the route cause I've switched to each of them. The issue is observed with latest redux packages at the time of my writing and solution is tested only against them

"react-redux": "^5.0.5",
"redux": "^3.7.1",
"redux-logger": "^3.0.6",
"redux-promise-middleware": "^4.3.0",
"redux-thunk": "^2.2.0"
anandhiyer commented 7 years ago

Thank you @savovsky for your reply. i had same issue in one of my projects and got resolved.

nguyentrithuc commented 6 years ago

Thanks @savovsky for your solution. It worked for me!

NickSevens commented 6 years ago

@mattdell facepalm +1, thanks for the .default hint :)

jfroussel commented 6 years ago

think you from PARIS .... Jeff

jfroussel commented 6 years ago

Thank you oupsss ..

nandorojo commented 5 years ago

use “import thunk from "redux-thunk";” not “import {thunk} from "redux-thunk";”

Thanks so much. Is there a way to make my linter recognize default imports properly? It's often at the core of these bugs. I found a plugin, but I'm not totally sure how to install it.

somayeh-ghasemipour commented 4 years ago

I had the same problem, and finally, I fixed the version of this : redux-thunk@2.3.0 and it worked!

HenryPineda commented 4 years ago

I had the same problem with redux-thunk@2.3.0 I fixed it by doing the following.

1- By reading a little bit of documentation here: https://redux.js.org/recipes/configuring-your-store

2- By add the following code

import {createStore, applyMiddleware, compose } from 'redux'; import thunkMiddleware from 'redux-thunk';

const middlewareEnhancer = applyMiddleware(logger, thunkMiddleware ); const composedEnhancers = compose(middlewareEnhancer,window.REDUX_DEVTOOLS_EXTENSION && window.REDUX_DEVTOOLS_EXTENSION());

const store = createStore(rootReducer,undefined, composedEnhancers);

anisur2805 commented 2 years ago

Simply add .default to the createStore function and solve the error Middlewareis not a function. This solve my issue.