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 ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

Vue 3 with Typescript - encountering a property that does not exist on the specified type error

I'm currently working on populating a component with leads fetched from an API. In my setup, I have a LeadService file and a Vue template file. The challenge I'm encountering is related to using an async call in my template file. Although the cal ...

Troubleshooting Angular HTTP: Issue with the HTTP request headers not updating

// assigning the httpclient protected _http: HttpClient = inject(HttpClient); // defining the options for the request const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/tcc' }), observe: 'resp ...

Dealing with useEffect being invoked twice within strictMode for processes that should only execute once

React's useEffect function is being called twice in strict mode, causing issues that need to be addressed. Specifically, how can we ensure that certain effects are only run once? This dilemma has arisen in a next.js environment, where it is essential ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

The model does not align with the body request, yet it is somehow still operational

My programming concept: class User { username: string; password: string; } Implementation of my function: const userList = []; function addUser(newUser: User) { userList.push(newUser); } Integration with Express router: router.post('/user ...

Fetching data for shadcn datatable in nextjs with axios

I am currently developing a website using NextJS 14 and Shadcn UI, incorporating Prisma and Axios. I am facing an issue while trying to display a datatable - it keeps returning a connection refused error and an unhandled runtime error. Despite extensively ...

SvgIcon is not a recognized element within the JSX syntax

Encountering a frustrating TypeScript error in an Electron React App, using MUI and MUI Icons. Although it's not halting the build process, I'm determined to resolve it as it's causing issues with defining props for icons. In a previous pro ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

Error TS2339: The 'selectpicker' property is not found on the 'JQuery<HTMLElement>' type

Recently, I integrated the amazing bootstrap-select Successfully imported bootstrap-select into my project with the following: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

Struggling to obtain the Variable

Trying to send a POST request to my ESP8266 HTTP Server, I need to transmit 4 variables: onhour, offhour, onminute, offminute. These variables should be retrieved from a timepicker-component imported from "ng-bootstrap" Despite numerous attempts over the ...

Why is my Angular Reactive form not retrieving the value from a hidden field?

I've encountered a problem where the hidden field in my form is not capturing the product id unless I manually type or change its value. It consistently shows as "none" when submitting the form. TS https://i.stack.imgur.com/W9aIm.png HTML https://i. ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

Drawing a real-time curve using Phaser 3

After reading the article at the following link, I am attempting to create a dynamic curve showing where a bullet intersects with the land in my game before firing. Any suggestions or ideas on how to achieve this would be greatly appreciated. Thank you. L ...

The TypeScript compiler encounters difficulties in locating type definitions when utilizing an inherited tsconfig file

There seems to be an issue with the functionality of tsconfig.json inheritance, specifically regarding the proper inheritance of the "typeRoots" setting. http://www.typescriptlang.org/docs/handbook/tsconfig-json.html (folder structure provided below) we ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

Container that displays vertical scroll while permitting floating overflows

Is there a way to set up a container so that when the window size is too small, it displays a scroll bar to view all elements that don't fit in one go? At the same time, can the child containing floating elements be allowed to extend beyond the bounda ...