Search code examples
graphqlgatsbysanity

How do you do CRUD in Gatsby with Sanity as my backend


I am now about knee-deep in a new Gatsby 4 project and may have hit a wall. I can't figure how to do CRUD in Gatsby with Sanity as my backend. Can I do GQL mutations in Gatsby GraphQL? I can't find any examples or tutorials anywhere.

I have done this in Next.js in a different project a but my backend was very different in my new project.

Any help is great.


Solution

  • I do not agree with @fstr's answer. All you can do in React can be done in Gatsby since it's a React-based framework.

    if you mean using Gatsby data layer and by that the graphql portion of it to apply a crud functionality in your site, then no. Gatsby's data layer is a "one way street" it's designed to pull in data, if you want to use mutations and/or subscriptions, you'll have to use something like Apollo to handle the mutations aspects of the data.

    This means that Gatsby fetches and gathers the data from the sources (like Strapi) when it builds the site (that's the one-way). The only thing you need to take into account is that because of Gatsby's staticity, you won't be able to create new pages on-demand (or on-the-fly) based on the user's input for example. If that's your scenario, you will need to trigger webhooks or to serve the site in the server, as Next and Gatsby v4 does.

    If your use-case is, for example, display some database (or Strapi) fields, manipulate/mutate them based on some user's actions/inputs, and fetch them again to display them on the screen you can easily do using any Apollo implementation as this article, and many other, explains (Implementing CRUD in web application using React and GraphQL). In this case, you won't be taking many benefits of using Gatsby rather than any other CRA or React site, but it can be done either way.

    So summarizing:

    • If you want to create dynamic pages based on some user's action, Gatsby won't help you much because you'll need to rebuild the site again, so it won't bypass the staticity.

    • If you want to mutate some data, send them back to the server, and display them again, it can be easily done.