DEV Community

Mat Warger
Mat Warger

Posted on • Edited on

6 5

AWS Amplify GraphQL Operations with TypeScript and Hooks - Part 3 [Mutations]

Let's take a quick look at mutations. This will be a short post, as Amplify makes mutations relatively painless, and the format of GraphQL mutations that we'll look at closely resemble the queries that we've already looked at (take a look at the previous posts in this series for more on that).

Mutations

To set up for mutations, we need to look at part of the query we did in the previous section.

const fetchQuery = async (query: string, variables?: VariablesType) => {
  try {
    setLoading(true);
    const { data } = (await API.graphql(
      graphqlOperation(query, variables)
    )) as {
      data: ResultType;
    };
    setData(data);
  } catch (error) {
    console.log(error);
    setError(error);
  } finally {
    setLoading(false);
  }
};
Enter fullscreen mode Exit fullscreen mode

All GraphQL API calls made with Amplify using the graphqlOperation function. We can reuse this, so let's make another function to handle the returning of data.

export const gqlOp = async <
  ResultType extends {},
  VariablesType extends {} = {}
>(
  query: string,
  variables?: VariablesType
) => {
  const { data } = (await API.graphql(graphqlOperation(query, variables))) as {
    data: ResultType;
  };
  return data;
};
Enter fullscreen mode Exit fullscreen mode

Now we can use this little function in place of the fetch call.

const fetchQuery = async (query: string, variables?: VariablesType) => {
  try {
    setLoading(true);
    const data = await gqlOp<ResultType, VariablesType>(query, variables)
    setData(data);
  } catch (error) {
    console.log(error);
    setError(error);
  } finally {
    setLoading(false);
  }
};
Enter fullscreen mode Exit fullscreen mode

Now that's done, let's create a function for mutations.

export const mutation = async <
  ResultType extends {},
  VariablesType extends {} = {}
>(
  query: string,
  variables?: VariablesType
) => gqlOp<ResultType, VariablesType>(query, variables);
Enter fullscreen mode Exit fullscreen mode

Alright, that's it. Thanks for reading!

Stay tuned for the next one where we tackle subscriptions.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay