Redux: Can't Dispatch Redux Action From Outside of Component (With Preloaded State)

Created on 27 Feb 2020  路  8Comments  路  Source: reduxjs/redux

Hello! I am having an issue where I am unable to dispatch actions from outside of a component. I have found many other people with this issue, but it seems that someone always submits an answer assuming that the "createStore" file always returns a store object:

However, my createStore file looks like this:

import { composeWithDevTools } from 'redux-devtools-extension';
import combinedReducers from './reducers/root-reducer';
import { load, save } from 'redux-localstorage-simple';
import { createStore, applyMiddleware } from 'redux';
import todosCustomMiddleware from './middlewares/todosCustomMiddleware';
import loginCustomMiddleware from './middlewares/loginCustomMiddleware';
import socketManager from './middlewares/socketManager';
import { ILoginState } from './reducers/login';
import { ITodosState } from './reducers/todos';
export interface IState {
  loginReducer: ILoginState,
  todosReducer: ITodosState
}
export default (preloadedState: IState) => {
  return createStore(
    combinedReducers,
    getLoadedState(preloadedState),
    composeWithDevTools(
      applyMiddleware(
        save({ states: ['loginReducer'] }),
        todosCustomMiddleware(),
        loginCustomMiddleware(),
        socketManager()
      )
    ),
  );
};
const getLoadedState = (preloadedState: IState | any) => {
  if (typeof window !== 'undefined')
    return {
      ...preloadedState,
      ...load({ states: ['loginReducer'], disableWarnings: true }),
    }
  return {
    ...preloadedState,
  }
}

And so then when I try to import it and call "dispatch" like this:

import store from './../state/createStore'
store.dispatch(loginSuccess())

Then the event is never handled by my middlewares/reducers, and I also get this typescript error:

Property 'dispatch' does not exist on type '(preloadedState: IState) => Store<{ loginReducer: ILoginState; todosReducer: { fetching: boolean; error: undefined; todos: any; } | { fetching: boolean; error: any; todos: never[]; }; }, AnyAction> & { ...; }'.

Is there any way for me to dispatch actions from outside of a component when I am syncing the state with localstorage? Thanks!

All 8 comments

Two observations:

First, we try to keep this repo reserved for actual bugs, not usage questions.

Second, as I just answered on Twitter, your code is wrong.

Your store.js is returning a function (call it configureStore) that actually generates and returns the store instance.

However, your import statement is treating that return value as the store itself, which is incorrect.

So, the correct usage would be:

import configureStore from './../state/createStore'
const store = configureStore()

store.dispatch(someAction)

Also, note that our new official Redux Toolkit package will do much of that store setup logic for you, and I strongly recommend you try using it.

Thanks!

Sorry, you may want to remove "Support / Usage Questions" from the options in the github issue template for this repo. 馃榿

Yes, you are correct @markerikson, After setting a default empty object preloadedState and making the properties of IState all optional I'm able to call configureStore with no typescript errors. Then actions are being handled properly. 馃憤 鉂わ笍

I'm curious about the Redux Toolkit, but I'm still confused as to what it actually is. Is it an npm package to use with redux? Is it a cli tool that generates code for you? something else?

Sorry, you may want to remove "Support / Usage Questions" from the options in the github issue template for this repo. 馃榿

@markerikson You might want to check out this nice PR in the react repo. https://github.com/facebook/react/pull/18039

The point of that "Support/Usage Questions" template entry is that users are supposed to _read_ what it says and go to Stack Overflow or Reactiflux :)

Redux Toolkit is an addon package that wraps the Redux core. Please read through the Redux Toolkit docs that I linked, including the tutorials.

@dai-shi : nice. Can you file PRs to add that to the Redux repos?

(May just be Redux and React-Redux atm, I don't think I've got issue templates set up for RTK.)

Pinging @ryota-murakami to see if he would be interested in filing PRs.

@dai-shi Thanks pinning 馃榾

@markerikson
I've just made PR and I chose reactflux url than stackoverflow., is it right?
https://github.com/reduxjs/redux/pull/3713

Fundamentally i think github_ discussion feature is ideal solution at the case.
AFAIK that's only available in Next.js repo, i hope public release this as soon as possible 馃

Was this page helpful?
0 / 5 - 0 ratings

Related issues

parallelthought picture parallelthought  路  3Comments

benoneal picture benoneal  路  3Comments

mickeyreiss-visor picture mickeyreiss-visor  路  3Comments

vslinko picture vslinko  路  3Comments

cloudfroster picture cloudfroster  路  3Comments