What is the best way to access redux store outside a react component?
react-redux, reactjs, redux
Solution
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.
MyStore.js
const store = createStore(myReducer);
export store;
or
const store = createStore(myReducer);
export default store;
MyClient.js
import {store} from './MyStore'
store.dispatch(...)
or if you used default
import store from './MyStore'
store.dispatch(...)
For Multiple Store Use Cases
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')
Problem
`@connect` works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that? This is my `api.js` ``` // tooling modules import axios from 'axios' // configuration const api = axios.create() api.defaults.baseURL = 'http://localhost:5001/api/v1' api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here api.defaults.headers.post['Content-Type'] = 'application/json' export default api ``` Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using `@connect` ``` // connect to store @connect((store) => { return { auth: store.auth } }) export default class App extends Component { componentWillMount() { // this is how I would get it in my react component console.log(this.props.auth.tokens.authorization_token) } render() {...} } ``` Any insights or workflow patterns out there?