Write Data in a DB Model in Blitzjs

Share this video with your friends

Send Tweet

Similar to The Blitz queries, mutations are also are plain, asynchronous JavaScript functions that always run on the server. And they must be inside a mutations folder

Mutations must be inside mutations folder

Example:

  • app/mutations/createPost.ts
  • app/posts/mutations/createPost.ts
  • app/admin/posts/mutations/createPost.ts

To write to the database you can use the db package e.g db.{modelName}.create.

Example:

import db, { PostCreateArgs } from "db"

type PostCreateInput = {
  data: PostCreateArgs["data"]
}

export default async function ({ data }: PostCreateInput) {
  const post = await db.post.create({ data })

  return post
}

To use the mutation client-side you can import it into your React Component directly.

Example:

import createPost from "app/posts/mutations/createPost"
const NewPost = () => {
  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault()
        const post = await createPost({
          data: { title: "new Title", slug: "new-post", content: "some new content" },
        })
      }}
    >
      <button type="submit">Create a new Random Post</button>
    </form>
  )
}

export default NewPost