Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blopa/b724d30d952fe222ab0e5cd5c3de31f9 to your computer and use it in GitHub Desktop.
Save blopa/b724d30d952fe222ab0e5cd5c3de31f9 to your computer and use it in GitHub Desktop.
Code for post "How to get the Redux State from a production build via the browser's console"
// 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);
@rossmeyerza
Copy link

rossmeyerza commented May 23, 2022

This was amazing, thank you! just a note. There is a small mistake on the traverse function - you are passing in the element but then not using it in the chained methods. This means that when you do recursion it won't traverse down the tree. So this
let store = internalRoot?.memoizedState?.element?.props?.store || internalRoot?.pendingProps?.store || internalRoot?.stateNode?.store;

should be let store = element?.memoizedState?.element?.props?.store || element?.pendingProps?.store || element?.stateNode?.store;

Thanks again, lifesaver.

@blopa
Copy link
Author

blopa commented Jun 1, 2022

@rossmeyerza oh wow, yeah, indeed! Nice catch! Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment