How to create Strapi entries in Nextjs with a Form (Apollo and GraphQL)

Viewed 13

I am trying to create new Strapi entries in Nextjs by submitting a form using Apollo client and GraphQL.

I tried a lot of diffrent things with my limited knowledge and was not able to make it work. While researching the topic I realized that most people are using the "useMutation" hook. It never worked though (also when using "useQuery" for queries). So I used a similar approach as for queries because they work.

queries: client.query | mutations: client.mutate

What I have tried:

// GraphQL that works in the Strapi playground
const TEST1 = gql`
  mutation CreateMitgliedanmeldung($name: String!) {
      createMitgliedanmeldung(data: { name: $name }) {
          data {
              attributes {
                  name
              }
          }
      }
  }`;

  export default function MitgliedWerden() {

    const formState = {
      name: ''
    };

    function updateFormState(key, value) {
      formState[key] = value;
    }

    function submit2() {
      console.log(formState.name);
      client.mutate({
        variables: { name: formState.name },
        mutation: TEST1,
      })
    }

    return (
      <div>    
          <form onSubmit={submit2()}>
            <input onChange={e => updateFormState('name', e.target.value)} id="name"></input>
            <button type="submit">Mitglied werden 1</button>
          </form>
      </div>
    )
  }

The code above creates new entries but there are multiple problems:

  • Variable "name" is not present in the new entry but can be console logged inside "updateFormState" function (same mutation works fine inside graphql playground)
  • Form is submitted when page is reloaded/loaded
  • When submitting the page reloads (this is fine if the other problems are gone)

To fix the reload problem I added the following and called it onSubmit.

// calling this onSubmit instead of submit2 function
const newsubmit = (e) => {
  e.preventDefault();
  submit2()
};

Now submitting or reloading the page does not create a new entry but I get the console.log with the correct value. It seems like the "client.mutate" is broken or can't work in those conditions. I was not able to find a lot about the ".mutate" function from apollo and the more often used "useMutation" hook did not work at all for me. Using "client.query" works fine.

Apollo Client:

import { ApolloClient, InMemoryCache } from "@apollo/client"

const defaultOptions = {
    query: {
        fetchPolicy: "no-cache",
    },
}

const client = new ApolloClient({
    uri: process.env.STRAPI_GRAPHQL_URL,
    headers: { "Authorization": process.env.STRAPI_TOKEN },
    cache: new InMemoryCache(),
    defaultOptions,
});

export default client

Dependencies:

"@apollo/client": "^3.6.9",
"@apollo/react-hooks": "^4.0.0",
"graphql": "^16.5.0",
"graphql-request": "^4.3.0",
"next": "12.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",

0 Answers
Related