Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch redux action outside of a component?

I'm using redux in my react-native mobile app.
The communication with the backend is via websockets using socket.io.

I organize the project in a way where I have a file (you could call it an object) which initialize the socket client.
The handlers are registered to it, and I want to send actions to the reducers.

socket.js:

export function createSocket (url) {
  console.log(`connecting to ${url}`)
  // dispatch(actions.CONNECT)
  return io(url)
}

How can I dispatch actions from those functions outside of any react component?

like image 571
itaied Avatar asked Jun 10 '18 20:06

itaied


People also ask

How do I access Redux outside of component?

You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.

How do I dispatch another action from reducer?

The app code dispatches an action to the Redux store, like dispatch({type: 'counter/incremented'}) The store runs the reducer function again with the previous state and the current action , and saves the return value as the new state.

How do I dispatch actions in Redux functional component?

There are two ways to dispatch actions from functional components: Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package.


1 Answers

If you initialise the socket client at startup time, just pass your redux store into the function and then use store.dispatch()

export function createSocket (url, store) {
  console.log(`connecting to ${url}`)
  store.dispatch(actions.CONNECT)
  return io(url)
}

If not at startup, then your socket creation should be triggered by some user action (or something similar) in which case you should be able to get a reference to the dispatch function using the redux-thunk middleware:

//the action returns a function, which gets called with store.dispatch as an argument
const myAction = someArg => dispatch => {
    createSocket(url, dispatch);
};

See https://github.com/reduxjs/redux-thunk for details

like image 171
Duncan Thacker Avatar answered Sep 26 '22 18:09

Duncan Thacker