Most of my project is built with React class components so I am looking for a solution that won't require me to refactor my class components to functional components. The problem I am having is that I have a file with some helper functions that enable calling an API. In that helper file, I also want to handle errors. One of my errors could result in logging the user out. In my App.js component, I have the following state and functions for logging a user out:
export const AppContext = React.createContext("app");
class App extends Component {
constructor() {
super();
this.state = {
loggedInStatus: "NOT_INITIALIZED",
user: {},
};
}
handleLogout = () => {
request.delete("/logout").then(response => {
this.setState({
loggedInStatus: "NOT_LOGGED_IN",
user: {},
});
}).catch(error => {
console.log("error", error);
});
};
render() {
return(
<AppContext.Provider
value={{
state: this.state,
handleLogout: this.handleLogout
}}
>
<BrowserRouter>
{code that renders certain pages}
</BrowserRouter>
</AppContext.Provider>
)
}
}
I've also created this HOC:
import React from 'react';
import {AppContext} from '../App.js'
export function withAppContext(Component) {
return function WrapperComponent(props) {
return (
<AppContext.Consumer>
{state => <Component {...props} context={state} />}
</AppContext.Consumer>
);
};
}
I can import and use this context in any of my class components and call the handleLogout function that is provided via the context. However, I have this helper file and I want to access the handleLogout function in the helper file rather than some child component. Here is my helper file:
import axios from 'axios';
const request = (function(){
function url(){
return window.$url;
}
return {
get: function(uri, params={}){
return axios.get(url() + uri, {withCredentials: true, params: params})
},
post: function(uri, data){
return axios.post(url() + uri, data, {withCredentials: true})
},
patch: function(uri, data){
return axios.patch(url() + uri, data, {withCredentials: true})
},
delete: function(uri){
return axios.delete(url() + uri, {withCredentials: true})
},
handleError: function(error){
//I want to call the handleLogout function here
}
}
})();
export default request;
I currently call these other helper functions from within a class component like so:
import request from "./RequestHelper";
class CustomerForm extends Component{
constructor(props){
super(props);
this.state = {
isSubmitting: false
}
}
handleSubmit = () => {
request.get("/someurl").catch((err) => {
//I call request.handleError(err) here
//which will log the user out depending on the error.
});
}
}
request(context).delete(......