import thunk from `redux-thunk` not working in stackblitz

51 Views Asked by At

Now I am trying basic redux logic in Stackblitz platform.

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

import taskReducer from './reducers/taskReducer';

const store = createStore(
  taskReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;

But when I add this code into src/store.js, the preview panel just shows blank page. And just when change this file not to use createStore or thunk, that works fine.. I am mostly sure this code is right, and I think this is just stackblitz issue.

So I want to know why this happening

Thanks for your help, community..

I am just trying now, and I hope to stackblitz works fine.

1

There are 1 best solutions below

0
Drew Reese On BEST ANSWER

In readux-thunk@3 there is no longer any default export, so with import thunk from "redux-thunk" thunk is undefined.

Compare v2

...

const thunk = createThunkMiddleware() as ThunkMiddleware & {
  withExtraArgument<
    ExtraThunkArg,
    State = any,
    BasicAction extends Action = AnyAction
  >(
    extraArgument: ExtraThunkArg
  ): ThunkMiddleware<State, BasicAction, ExtraThunkArg>
}

// Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
thunk.withExtraArgument = createThunkMiddleware

export default thunk

to v3

...

function createThunkMiddleware<
  State = any,
  BasicAction extends Action = AnyAction,
  ExtraThunkArg = undefined
>(extraArgument?: ExtraThunkArg) {
  // Standard Redux middleware definition pattern:
  // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
  const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
    ({ dispatch, getState }) =>
    next =>
    action => {
      // The thunk middleware looks for any functions that were passed to `store.dispatch`.
      // If this "action" is really a function, call it and return the result.
      if (typeof action === 'function') {
        // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
        return action(dispatch, getState, extraArgument)
      }

      // Otherwise, pass the action down the middleware chain as usual
      return next(action)
    }
  return middleware
}

export const thunk = createThunkMiddleware()

...

Update your code to import the named thunk export.

import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk'; // <-- import named export
import { composeWithDevTools } from 'redux-devtools-extension';

import taskReducer from './reducers/taskReducer';

const store = createStore(
  taskReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;