All Guides Setting up React Native with Prisma

Setting up React Native with Prisma

In this short guide, you will learn how to set up React Native with Prisma and SQLite to perform CRUD on the database.

Install Prisma Package

Install the following packages to your project.

npx expo install @prisma/client @prisma/react-native react-native-quick-base64

Next, update the project Expo config to add the Prisma plugin.

// app.json

{
  "expo": {
    "plugins": ["@prisma/react-native"]
  }
}

Re-run the prebuild with the clean flag.

npx expo prebuild --clean

Define Prisma Configuration

To define the Prisma schema you can create a new file in the project root folder. The schema defined here specifies the client, datasource and model used for the project.

// schema.prisma

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["reactNative"]
}

datasource db {
  provider = "sqlite"
  url      = "file:./app.db"
}

model User {
  id           Int     @id @default(autoincrement())
  name         String
}

model Post {
  id           Int     @id @default(autoincrement())
  title        String
}

To initiate the migration and create the database file, run the following Prisma migration and generate the Prisma client.

npx prisma@latest migrate dev && npx prisma@latest generate

Query the Database

To query the database you can define a new file to initialize the Prisma client.

// dbModule.ts

import { PrismaClient } from '@prisma/client/react-native';
import { reactiveHooksExtension } from '@prisma/react-native';

const baseClient = new PrismaClient();

export const extendedClient = baseClient.$extends(reactiveHooksExtension());

Now you may call any of the query functions from all your screens.

import { Text } from 'react-native';
import { extendedClient } from './dbModule';

export default function App {
  const users = extendedClient.user.useFindMany();

  return (
    <Text>{users}</Text>
  )
}

Introducing NeNews React Native UI Kit

HestiaKit Premium

You have to be signed in to favorite this screen

Share

HestiaKit Premium

This is HestiaKit premium component