coding

How to get the Redux State in production via the browser's console

Written in February 20, 2022 - 🕒 1 min. read

EDIT: This only works for React 17 or lower, for React 18 check this blog post.

Sometimes 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?

redux state on instagram

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 =
    element?.memoizedState?.element?.props?.store
    || element?.pendingProps?.store
    || element?.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].map((store) => store.getState()).

See you in the next one!

Tags:


Post a comment

Comments

Anon on 3/20/24

Is there any way to prevent it?