graphqlnuxt.jsapollostrapi

Execute GraphQL mutation via Apollo on NuxtJS


I know that to execute a GraphQL query via Apollo on NuxtJS 2, we can do like this :

import articlesQuery from "~/apollo/queries/articles/recent-articles";

export default {
  data() {
    return {
      articles: {
        data: [],
      },
  },
  apollo: {
    articles: {
      prefetch: true,
      query: articlesQuery,
    },
  },
};

But to execute a mutation (to create an entry in Strapi Content Manager for exemple), I couldn’t find very much informations.

I was trying this way, but unsuccessfully :

import createPost from "~/apollo/queries/actualitesEtNewsletters/createArticle";

export default {
  apollo: {
    createActualitesEtNewsletters: {
      mutation: createPost,
      context: {
        headers: {
          authorization:
            "Bearer JWT_TOKEN",
        },
      },
    },
  },
};

Feel free to ask for additional informations.

Thank you !


Solution

  • I found the solution ! :

    export default {
      methods: {
        createPost() {
          this.$apollo
            .mutate({
              mutation: createPost,
              context: {
                headers: {
                  authorization:
                    "Bearer JWT_TOKEN",
                },
              },
            })
            .then((data) => {
              console.log(data);
            })
            .catch((error) => {
              // Error
              console.error(error);
            });
        },
      },
      mounted() {
        this.createPost();
      },
    };