I have a a helper function that I call when I want to delete something from my redux store. However I need to be able to access the current store inside the function to make a determination on what to do next. Here's what I want to do:
export function deleteDocument (id) {
this.props.dispatch(deleteShape({id}));
const getStore = getStore(); //<-- I need something like this
if(getStore.documents && !getStore.documents.find(doc => doc.selected)){
this.props.dispatch(makeTopDocumentSelected());
}
}
I call this function from a component and pass the "this" context to it so it will have access to dispatch if you're curious about that. But if I try to reference a prop that I pass along it doesn't update after the "deleteShape" call because this function is not "connected" (for lack of a better word) to the redux store. So my question is this: how can I access the current redux store from non-component functions? Thanks
You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.
redux state can be accessed as prop in a function by using below format. 1: import { connect } from 'react-redux'; // log accepts logMessage as a prop function log(props) { const { environment, logMessage } = props; console. debug('environment' + environment + logMessage ); .... }
STEP-1 import useStore first from react-redux and then getState() function is used to access store state. STEP-2 area is the name of my slice in Redux store and areaName is state in that slice. STEP-3 FiletoSave variable is used to export JSON file with data from store.
To trigger a Redux action from outside a component with React, we call store. dispatch from anywhere in our project. import { store } from "/path/to/createdStore"; function testAction(text) { return { type: "TEST_ACTION", text, }; } store.
I must say that I think it's a bad practice to randomly access the store from some function, and some side effects may occur, but if you have to do it this is a possible way:
file: storeProvider.js
var store = undefined;
export default {
init(configureStore){
store = configureStore();
},
getStore(){
return store;
}
};
file: App.js
import { createStore } from 'redux';
import rootReducer from './rootReducer';
import storeProvider from './storeProvider';
const configureStore = () => createStore(rootReducer);
storeProvider.init(configureStore);
const store = storeProvider.getStore();
const App = () =>
<Provider store={store} >
<Stuff/>
</Provider>
file: yourfunction.js
import storeProvider from './storeProvider';
export function deleteDocument (id) {
this.props.dispatch(deleteShape({id}));
const state = storeProvider.getStore().getState();
if(state.documents && !state.documents.find(doc => doc.selected)){
this.props.dispatch(makeTopDocumentSelected());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With