is it possible to dispatch a redux function from a javascript object that is not part of react's component?
Usually when i wish to dispatch an action, i would do the following:
I'll map the dispatch function to the component's props:
const mapDispatchToProps = dispatch => {
return {
autoCheckState: () => dispatch(actions.authCheckState()),
}
}
And then i can just call the dispatch function like this:
async componentDidMount() {
await this.props.autoCheckState();
this.setState({
checking:false
})
}
However, now i wish to call the dispatch function from within my axiosinterceptor object, and they don't have "props"
Here is what i envisioned would be the way to use it, but ofcourse it does not work:
axiosInstance.interceptors.response.use(
response => {
return response
},error => {
######## bunch of code that is not relevant ##########
this.props.updateTokens(response.data.access,refreshToken) #<--- how i would call it if i based it off the first example
######## bunch of code that is not relevant ##########
return Promise.reject(error);
}
);
const mapDispatchToProps = dispatch => { ##<--- maping the dispatch to the 'props'
return {
updateTokens: () => dispatch(actions.authSuccess())
}
}
export default connect(mapStateToProps,mapDispatchToProps)(axiosInstance);
Ofcourse the above would give me the error that this is not defined, since its not a class. May i know the correct way of using redux in such a situation?
You can make use of store.dispatch to dispatch an action from outside of your components or action creators
import store from '/path/to/store';
axiosInstance.interceptors.response.use(
response => {
return response
},error => {
store.dispatch(actions.authSuccess(response.data.access,refreshToken));
return Promise.reject(error);
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.