Prisma Remix is throwing a TypeError: "The function (0, import_prisma.createNote) is not defined as a function."

In my project, I wrote a function using the prisma client which is being called from the notes.tsx route in remix.

export async function createNote(entity: { title: string, description: string }) {
    const note = await prisma.note.create({
        data: {
            title: entity.title,
            description: entity.description,
            userId: mainUser.id,
        },
    });
    console.log(note);
    return note;
}

The action defined in the notes.tsx route which utilizes the createNote function is as follows:

export async function action(data: any) { const { request } = data; const formData = await request.formData(); console.log(formData, ...formData.entries());

const noteData: Note = {
    title: formData.get("title")?.toString() ?? "",
    description: formData.get("description")?.toString() ?? "",
};

const note = await createNote(noteData);
console.log(`New note created => Note:`, note);

}

When attempting to execute the code, an error occurs instead of creating a new record in the database,

TypeError: (0 , import_prisma.createNote) is not a function
    at action (file:///Users/user/workspaces/ts/remix-workspace/project/app/routes/notes.tsx:27:24)

I have identified the issue. It seems that any functions exported from the prisma client to remix are not functioning properly. Despite correctly defining the function, upon testing with another function in prisma client, I encountered the same error indicating that the new function does not exist. How can this issue be resolved? Thank you.

Answer №1

Discovered that using prisma.client directly in a route in remix is not possible. Instead, I had to create a db.server.ts file which passes a reference to the database helper, allowing it to be used in remix routes. Take a look at the code snippet below,

In the db.server.ts file,

import { PrismaClient } from "@prisma/client";

declare global {
    var __prisma: PrismaClient;
}

if (!global.__prisma) {
    global.__prisma = new PrismaClient();
}

global.__prisma.$connect();

export const prisma = global.__prisma;

Create your helper.ts file wherever you prefer and add the following code,

import { prisma } from "../db.server";
    
export async function createNote(entity: any) {

    const note = await prisma.note.create({
      data: {
        title: entity.title,
        description: entity.description,
        userId: mainUser.id,
      },
    });
}

You can now call this function within your route's action with success.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

Tips for creating an effective update method in Prisma

I need help fixing my PUT method in Prisma to update all plan connections when updating my checkout this.connection.update({ where: { id }, data: { name, description, picture, updatedAt: new Date(), plans ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

What is the best way to add a custom typeguard to an object in TypeScript?

Looking to implement a type guard as an object method? I have an array of objects with similar data structures, but crucial differences that need to be checked and guarded using TypeScript. interface RangeElement extends Element { value: number; } inter ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Triggering an event within a component to execute a specific function in another component

I am working on a component that includes multiple routes such as home, app, and navbar. My goal is to have the encrementcalc() function execute when the navbar button is pressed. I attempted to use the event emitter but was unsuccessful. Can someone prov ...

Implement a default dropdown menu that displays the current month using Angular and TypeScript

I am looking to implement a dropdown that initially displays the current month. Here is the code snippet I have used: <p-dropdown [options]="months" [filter]="false" filterBy="nombre" [showClear] ...

Isolating a service from a component based on conditions in Angular 5

Within my root module, I have a service that is shared among all components. One of these components is named ComponentX module providers: [ BiesbroeckHttpService ], component constructor(private biesbroeckHttpService: BiesbroeckHttpService){} Som ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

Guide on restricting object keys to a specific set of strings in typescript

I am dealing with an API that has the ability to return one of these options: { fill: 'string'} or {stroke: 'string'} or {effect: 'string'} The key type I have established is as follows: type StyleKeyType = | 'fill&a ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

When attempting to import the image path from a JSON file, a ReferenceError occurs stating that the data variable is not

I'm currently attempting to iterate through image paths in a JSON file and display them in a browser using the "img" tag. While hardcoded values work perfectly fine, I encountered an issue when trying to switch to a variable as outlined in this post: ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Ways to duplicate package.json within a Dockerfile

My issue revolves around the challenge I am facing while attempting to copy my package.json to the Dockerfile context. Below is a representation of my file structure: src - apps -- api --- Dockerfile - docker -- tcp --- docker-compose.yml - package.json H ...

The close button in Angular 4 is unresponsive until the data finishes loading in the pop-up or table

Having trouble with the Close button in Angular 4 popup/table The Pop Up is not closing after clicking anywhere on the screen. I have added backdrop functionality so that the pop-up closes only when the user clicks on the close icon. However, the close i ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

Data is not being successfully transmitted through the ORM (Prisma) to the database

After spending hours trying to solve this issue, I've hit a roadblock. My current project is using Next.js 13. I managed to successfully connect my application to a Postgres Database, configure the Prisma schema, and test a migration with a seed.ts f ...