question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

14reactions
markeriksoncommented, Feb 27, 2020

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.

2reactions
markeriksoncommented, Feb 27, 2020

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

reactjs - Is it possible to trigger a Redux action from outside a ...
In order to dispatch and action from outside of the scope of React.Component you need to get the store instance and call dispatch...
Read more >
Access the Redux Store Outside a React Component
If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store.dispatch() ...
Read more >
Redux Fundamentals, Part 4: Store
The Redux store brings together the state, actions, and reducers that make up your app. The store has several responsibilities:.
Read more >
React useReducer Hook ultimate guide - LogRocket Blog
Component state for component state, Redux for application state. ... We dispatch action objects to that reducer only, whereas in Redux, ...
Read more >
Redux Outside of React | Aten Design Group
Enter Redux: a minimal JavaScript framework for managing state in these types of ... Dispatch click action → Update coordinates reducer ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found