Home > Net >  Update redux state outside React component
Update redux state outside React component

Time:07-30

I have a react project configured with redux for state management. For api calls I use a file called axiosInstance. In this file I need to have access to redux store (and I have access importing store and using getState - store.getState()). Now the problem is that I want also to update the redux state from this file (axiosInstance). How I can update redux store from this file (which is not a react component) in a efficient method?

CodePudding user response:

Okay, I assume that you are using Axios for the network calls.

tl;dr

Use store.dispatch(action) and action to make changes to store state

Yes, the store can be accessed with store.getState(), you can also change state with store.dispatch(action). as per the docs

Dispatches an action. This is the only way to trigger a state change.

The store's reducing function will be called with the current getState() result and the given action synchronously. Its return value will be considered the next state. It will be returned from getState() from now on, and the change listeners will immediately be notified.

This happens because of the functional paradigm that redux follows (google for more).

Now, the action has to be defined with an actionCreator, or simply you could call .dispatch() with an inline object with one string property as {type: 'name-of-action'}. This prompts the store to change the state. You may require redux-thunk for async actions.

Conclusion:

Let's save some trouble here as you may have many calls to the store, you can create a context that handles the AxiosInstance (as there is already a different file for that).

Make a context in the AxiosInstance file and then you can start dispatching actions as per the network responses. this will save you a lot of trouble as the state is updated by redux without actually looking at it much.

  • Related