How do I access the Redux store outside a React component? first import the store from your storeConfig file and to get the reducer state you can use store. getState(); you will get an object and after that you can use the values using keys.
To access the store in non-component front end code, I used the analogous import (i.e., import {store} from "../../store. js" ) and then used store. getState() and store. dispatch({*action goes here*}) to handled retrieving and updating (er, sending actions to) the store.
To trigger a Redux action from outside a component with React, we call store. dispatch from anywhere in our project. import { store } from "/path/to/createdStore"; function testAction(text) { return { type: "TEST_ACTION", text, }; } store.
Export the store from the module you called createStore
with. Then you are assured it will both be created and will not pollute the global window space.
const store = createStore(myReducer);
export store;
or
const store = createStore(myReducer);
export default store;
import {store} from './MyStore'
store.dispatch(...)
or if you used default
import store from './MyStore'
store.dispatch(...)
If you need multiple instances of a store, export a factory function.
I would recommend making it async
(returning a promise
).
async function getUserStore (userId) {
// check if user store exists and return or create it.
}
export getUserStore
On the client (in an async
block)
import {getUserStore} from './store'
const joeStore = await getUserStore('joe')
Found a solution. So I import the store in my api util and subscribe to it there. And in that listener function I set the axios' global defaults with my newly fetched token.
This is what my new api.js
looks like:
// tooling modules
import axios from 'axios'
// store
import store from '../store'
store.subscribe(listener)
function select(state) {
return state.auth.tokens.authentication_token
}
function listener() {
let token = select(store.getState())
axios.defaults.headers.common['Authorization'] = token;
}
// configuration
const api = axios.create({
baseURL: 'http://localhost:5001/api/v1',
headers: {
'Content-Type': 'application/json',
}
})
export default api
Maybe it can be further improved, cause currently it seems a bit inelegant. What I could do later is add a middleware to my store and set the token then and there.
You can use store
object that is returned from createStore
function (which should be already used in your code in app initialization). Than you can use this object to get current state with store.getState()
method or store.subscribe(listener)
to subscribe to store updates.
You can even save this object to window
property to access it from any part of application if you really want it (window.store = store
)
More info can be found in the Redux documentation .
You can use Middleware
according to How can I access the store in non react components?:
function myServiceMiddleware(myService) {
return ({ dispatch, getState }) => next => action => {
if (action.type == 'SOMETHING_SPECIAL') {
myService.doSomething(getState());
myService.doSomethingElse().then(result => dispatch({ type: 'SOMETHING_ELSE', result }))
}
return next(action);
}
}
import { createStore, applyMiddleware } from 'redux'
const serviceMiddleware = myServiceMiddleware(myService)
const store = createStore(reducer, applyMiddleware(serviceMiddleware))
Further Reading: Redux Docs > Middleware
Like @sanchit proposed middleware is a nice solution if you are already defining your axios instance globally.
You can create a middleware like:
function createAxiosAuthMiddleware() {
return ({ getState }) => next => (action) => {
const { token } = getState().authentication;
global.axios.defaults.headers.common.Authorization = token ? `Bearer ${token}` : null;
return next(action);
};
}
const axiosAuth = createAxiosAuthMiddleware();
export default axiosAuth;
And use it like this:
import { createStore, applyMiddleware } from 'redux';
const store = createStore(reducer, applyMiddleware(axiosAuth))
It will set the token on every action but you could only listen for actions that change the token for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With