How to get the Redux State from a production build via the browser's console
Written in February 20, 2022 - 🕒 1 min. readSometimes you want to debug the Redux State from your application on production, but you don’t have redux-devtools enabled for production, so what can you do?
TL;DR
Run this on the browser’s console.
const internalRoot = Array.from(document.querySelectorAll("*[id]")).find((el) => el?._reactRootContainer?._internalRoot?.current)?._reactRootContainer?._internalRoot?.current;
const state = (internalRoot?.pendingProps?.store || internalRoot?.stateNode?.store || internalRoot?.memoizedState?.element?.props?.store)?.getState?.();
The long version
Recently I had to debug a problem in production which I needed to access the Redux State, so I came across this solution, which needed React DevTools to be installed in the browser, and that worked for me, but then I wondered how that could be done without the use of any extensions.
After a bit of researching I found this solution on Stack Overflow, which lead me to create the following script:
// Traverse a dom element
const stores = new Set();
const traverse = (element) => {
let store =
internalRoot?.memoizedState?.element?.props?.store
|| internalRoot?.pendingProps?.store
|| internalRoot?.stateNode?.store;
if (store) {
stores.add(store);
}
if (element.child) {
traverse(element.child);
}
};
// Find the root element for React
const reactRoot = Array.from(document.querySelectorAll("*[id]")).find((el) => el?._reactRootContainer?._internalRoot?.current);
const internalRoot = reactRoot._reactRootContainer._internalRoot.current;
// Traverse the root react element to find all Redux States in the app
traverse(internalRoot);
After running this script, all Redux States will be available inside the variable stores
, and you can access them via stores.forEach((store) => store.getState())
.
See you in the next one!