Reputation: 23
In our react.js website we made a javascript file that contains the base url to create axios and write the code only once and use it whenever we went to send request to the database , the problem is we need to access Redux from this normal javascript file which is not a component . is there a way to access redux from it?
Upvotes: 2
Views: 1638
Reputation: 2844
Need to call getState
from store. Here is an example:
store.js
import { createStore } from 'redux'
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
let store = createStore(counter)
export { store }
normal-javascript-file.js
import { store } from './store.js'
// you can call getState() to get current store state.
console.log(store.getState())
If your normal javascript file is not bundled with react-app, you need to assign store instance to window object to make it globally available everywhere:
store.js
import { createStore } from 'redux'
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
let store = createStore(counter)
window.appStore = store
export default store
normal-javascript-file.js
var store = window.appStore
console.log(store.getState())
Upvotes: 5