I cannot access my service class methods when I convert the export to service rather than methods:
const HttpService = () => {
const AUTH_TOKEN = localStorage.getItem("tokenKey");
const { enqueueSnackbar } = useSnackbar();
const postWithoutAuth = (url, body) => {
const request = axios.post(url, body);
return request.then((response) => response.data);
};
};
export default HttpService;
I am trying to access the postWithoutAuth
method as shown below:
import { HttpService } from "../../services/HttpService";
// I think I should use like this:
import HttpService from "../../services/HttpService";
const handleSubmit = (event) => {
event.preventDefault();
HttpService.postWithoutAuth("/auth/signup", formValues)
.then((response) => {})
.catch((error) => {});
};
So, is it a proper way to call this service method?
2
Answers
It is impossible to access a function declared inside another function that is not returned in some way.
HttpService
does not look like it should be a function at all. Instead, you can directly export thepostWithoutAuth
function.Then, you can use it in another file like so:
don’t make
HttpService
a function but just a file in which you include all the functions you want to export :Now you can import from it :
Update to reply to the op question update:
If you want to use a hook from the
postWithoutAuth
function then you pass a function to it from the parent component that uses the hook becausefrom the parent component :
You can make multiple functions similar to the
functionHook
in your parent component that display different alerts and you can also pass more then one function the thepostWithoutAuth
function and based on theresponde.data
you know what function to execute