Search code examples
gatsbystatic-sitestrapiheadless-cms

How to mutate data in Strapi with a site made with Gatsby?


I wanted to know if it's possible to write mutation querys in a site made with gatsby. The data I want to create in Strapi will not be used to display new information, it will just store data.

Is there any approach to do this? From what I've read, Gatsby by itself won't mutate Strapi data.


Solution

  • You need provide ApolloClient to your website. The best way will be in your root in gatsby-ssr.js and gatsby-browser.js after that you can use react-apollo like in bellow examples

    client.js

    import ApolloClient from "apollo-boost"
    
    const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDRhN2FlNjRlYzE1MzIxMTY0N2EzNWMiLCJpc0FkbWluIjp0cnVlLCJpYXQiOjE1NjU1OTI2ODcsImV4cCI6MTU2ODE4NDY4N30.FZIWJ7sWhmQo6MPgUbY2Js-uVMWY1kUdASvr2oyY6Sd"
    const url = "http://localhost:1337"
    
    export default new ApolloClient({
      uri: `${url}/graphql`,
      request: operation => {
        operation.setContext({
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
      },
    })
    

    gatsby-ssr.js and gatsby-browser.js

    
    import React from 'react';
    import { ApolloProvider } from 'react-apollo';
    import { client } from './src/client';
    
    export const wrapRootElement = ({ element }) => (
      <ApolloProvider client={client}>
        {element}
      </ApolloProvider>
    );
    

    postTemplate.js

    import React from "react"
    import { Mutation } from "react-apollo"
    import gql from "graphql-tag"
    
    const POST_MUTATION = gql`
      mutation PostMutation($description: String!, $url: String!) {
        post(description: $description, url: $url) {
          id
          createdAt
          url
          description
        }
      }
    `
    const PostTemplate = () => {
      const description = "example description"
      const url = "url"
    
      return (
        <Mutation mutation={POST_MUTATION} variables={{ description, url }}>
          {() => <button onClick={"... you'll implement this 🔜"}>Submit</button>}
        </Mutation>
      )
    }
    
    Export default PostTemplate
    

    Other links