How to run Queries/mutation outside of react components

Hi Everyone,
I have js file with multiple helper function which i call and use from many different components. Currently i call an API and that API does its thing and return some value.
I want to replace it with a graphQL mutation call which in turn will call an hasura action.

How can i call useMutation outside the functional react component.?
Any help is appreciated

Instead of trying to use useMutation outside of a component (won’t work…), I would suggest just getting the instance of the Apollo Client, and call mutate directly on it, await the results, and return whatever you need to the caller.

Thank you so much for replying. Can I see a code snippet or forum where I can refer to code .
Sorry for asking but I am new to graphql world. Any pointer will be highly appreciated.
Thanks you

I have a utility file for my Apollo Client instance called apolloClient.js. Basic stuff in here:

const client = new ApolloClient({
    link: ApolloLink.from([errorLink, link]),
    cache,
    resolvers
});

export default client;

Then, anywhere else in my code, such as a components, I can just import that client and call query/mutate on it:

// SomeComponent.jsx

import apolloClient from '-/graphql/apolloClient';
import {someMutation} from '-/graphql/wheverer';

const MyComp = props => {
    const onClick = async() => {
        const results = await apolloClient.mutate({
            mutation: someMutation,
            variables: {...}
        });
    };

    return (
         <div onClick={onClick}>
             <i className="fas fa-trash" /> Delete
         </div>
    );
};

export default MyComp;
1 Like