Server Actions and this Keyword #74124
-
SummaryI am trying out Next 15, RSC for the first time. However, I ran into an issue when I am trying to run a sqlite db query within my server action. Is there any better solutions than writing an API for it? I am using the 'use server';
import { db } from "./database";
export const createItem = async (title: string): Promise<number> => {
if (!title) {
throw new Error("Title is required");
}
return new Promise((resolve, reject) => {
db.serialize(() => {
db.run(
`
INSERT INTO items (title) VALUES ($title)
`,
{
$title: title
},
function(err) {
if (err) {
reject(err);
}
resolve(this.lastID);
}
)
})
})
} Attempt to do that will cause the following error message: Import trace for requested module:
./src/app/api/checklist.ts
./src/ui/create-item-input.tsx
⨯ ./src/app/api/checklist.ts
Error: × Server Actions cannot use `this`.
│
╭─[D:\Developments\checklist-app\src\app\api\checklist.ts:24:1]
21 │ reject(err);
22 │ }
23 │
24 │ resolve(this.lastID);
· ────
25 │ }
26 │ )
26 │ })
╰────
Import trace for requested module:
./src/app/api/checklist.ts
./src/ui/create-item-input.tsx I am not sure why it is Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 18 replies
-
Alright, so this is by design, #73059 - Are you trying to use it as a global to store data? I am trying to figure out exactly why is it forbidden, but looks like you'd need to change your approach anyway. |
Beta Was this translation helpful? Give feedback.
-
@jintaokoong I tried to replicate but it somehow works without mentioned error. Testing on |
Beta Was this translation helpful? Give feedback.
-
Hi guys, sorry for the delayed response. Here is the public repository where I got the error to reproduce. https://github.com/jintaokoong/next-app-this Thanks for all the responses, really appreciate the help. |
Beta Was this translation helpful? Give feedback.
-
SQL insert has an optional Here is export const createItem = async (title: string) => {
return new Promise<number>((resolve, reject) => {
db.serialize(() => {
db.all(
`
INSERT INTO items (title) VALUES ($title) RETURNING id;
`,
{
$title: title
},
function (err, rows: {id: number}[]) {
if (err) {
reject(err);
}
resolve(rows[0].id);
}
)
})
});
}; |
Beta Was this translation helpful? Give feedback.
-
Somehow, I feel the topic is still open. What are you,
|
Beta Was this translation helpful? Give feedback.
SQL insert has an optional
RETURNING *
part.It will return data of just created row(s).
And its supported also in sqlite.
Here is
createItem
rewriten to use it: