I have unit tests for my reducers
, as I'm supposed so have. However, when I'm debugging in the browser, I want to check if my actions have been called correctly and whether the state has been modified accordingly.
I'm looking for something like:
window._redux.store
... in the browser so I can type that on the console and check how things are going.
How can I achieve that?
If you have react developer tools running you can use $r.store.getState();
with no changes to your codebase.
Note: You have to open the react devtool in your developer tools window first to make this work, otherwise you will get a $r is not defined
error
- open developer tools
- click the React tab
- ensure the provider node (or topmost node) is selected
- then type
$r.store.getState();
or $r.store.dispatch({type:"MY_ACTION"})
into your console
let store = createStore(yourApp);
window.store = store;
Now you can access the store from window.store in the console like this:
window.store.dispatch({type:"MY_ACTION"})
You can use a logging middleware as described in the Redux Book:
/**
* Logs all actions and states after they are dispatched.
*/
const logger = store => next => action => {
console.group(action.type)
console.info('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
console.groupEnd(action.type)
return result
}
let createStoreWithMiddleware = applyMiddleware(logger)(createStore)
let yourApp = combineReducers(reducers)
let store = createStoreWithMiddleware(yourApp)
Alternatively, you could change the logging to just append to a global array (your window._redux
) and you could look in the array when you needed information on a particular state.
In case you would like to see store state for debugging you could do this:
#import global from 'window-or-global'
const store = createStore(reducer)
const onStateChange = (function (global) {
global._state = this.getState()
}.bind(store, global))
store.subscribe(onStateChange)
onStateChange()
console.info('Application state is available via global _state object.', '_state=', global._state)
If you're using Next JS, you can access the store by: window.__NEXT_REDUX_STORE__.getState()
You can also dispatch actions, just look at the options you have in window.__NEXT_REDUX_STORE__