Skip to content

Instantly share code, notes, and snippets.

@fmg-lydonchandra
Last active February 2, 2024 06:06
Show Gist options
  • Save fmg-lydonchandra/c25a7e3f35c190def6c3f3e3a3b19e91 to your computer and use it in GitHub Desktop.
Save fmg-lydonchandra/c25a7e3f35c190def6c3f3e3a3b19e91 to your computer and use it in GitHub Desktop.
var store = getReduxStore();
var state1 = store.getState();
console.log(state1);
store.dispatch({
type: 'myType/myAction',
payload: { payloadField: true }
})
function getReduxStore() {
// 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);
var reduxStore;
[...stores].forEach((store) => {
// todo: more validations
if (store.getState()) {
reduxStore = store;
return;
}
})
return reduxStore;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment