How can I pass a value into a function without using function parameters?

128 Views Asked by At

I have a factory function that returns a React Query mutation hook, like this:

function useMutationFactory(mutationFunction: (axios: Axios) => (params: any) => any) {
    const baseURL = getBaseURL(); // Retrieves the Base URL (this is dynamic)
    const axios = useAxios({baseURL}); // Creates an Axios instance with the URL
    ...
    return useMutation(mutationFunction(axios));
}

The usual mutation function for useMutation is (params: any) => any, I have to curry it to pass axios to the user. I want to see if it's possible to have axios inside of mutationFunction without currying.

The idea I have is to use prototypes, and write wrapper functions for every axios http method. Something like this:

const Mutation = {
    queryGet: (...params: Parameters<Axios["get"]>) => {
        const axios = this.prototype.axios; // Not sure about this part
        return axios.get(...params);
    }
}

The mutation function from users would be something like this:

const mutation = useMutationFactory((params) => {
     const res = Mutation.queryGet("/");
});

I'm stuck on getting axios to Mutation. Ideally, axios isn't passed to the user, so I have to set axios inside useMutationFactory. I can't use apply() or call(), since the user would have to call that (I'm assuming). I'm still very new at Object prototyping, so I would appreciate any suggestions or help!

1

There are 1 best solutions below

3
Fishbite On

Well, have the function do something with a variable in the global scope, update / change the variable in the global scope to the value you want to pass to the function, then call the function so that it reads the updated value of the variable.

I'm on my phone atm else I would give a code example. Hope this helps though.