Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Dispatch function from a blank javascript file

So i'm writing a React-Redux web app, and i call dispatch from my react components like this :

this.props.dispatch(someAction());

Now i need to call dispatch from a javascript function that is not a React Component, so how do i import the dispatch function and use it in this case ? Thank you.

like image 979
Meshredded Avatar asked Jul 11 '17 19:07

Meshredded


People also ask

How do I dispatch an outside component?

If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store. dispatch() , passing the action you need to dispatch. It works the same as the dispatch function you get from props via react-redux's connect function.

How do you dispatch a function?

On the first call, the state is the return value of the initialization function. On subsequent calls, it is the state at the time of the call. const [ state, dispatch ] = useReducer(reducer, initArgument, initFunction); Use the dispatch function to dispatch actions to the reducer.

What is the input for the dispatch function?

The dispatch function is in the same scope as the current state of the app. So that means that inside the dispatch function, we have access to an object called currentState that is the current state in our app. In that same scope is the reducer function that we have written and passed into createStore or useReducer .

What does Dispatch mean in Javascript?

dispatch is a function of the Redux store. You call store. dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.


2 Answers

The dispatch function is a member of your redux store. If you created and exported your store in a module, it would be as easy as importing the store in your module and calling the dispatch function.

Example:

// store.js
import { createStore } from 'redux'

export default createStore(reducers)


// somefile.js
import store from './store'

store.dispatch(someAction)
like image 130
forrert Avatar answered Oct 14 '22 04:10

forrert


The dispatch method is one of the store's methods. react-redux makes dispatch available to components as props via the provider, and mapDispatchToProps.

You can dispatch directly from the store:

store.dispatch(action)
like image 2
Ori Drori Avatar answered Oct 14 '22 02:10

Ori Drori