Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Last active January 9, 2022 04:09
Show Gist options
  • Save dipeshhkc/ce262b790370e54e4ad82c6b15ea07f9 to your computer and use it in GitHub Desktop.
Save dipeshhkc/ce262b790370e54e4ad82c6b15ea07f9 to your computer and use it in GitHub Desktop.
import { ActionFunction, json, redirect } from 'remix';
import { db } from '~/utils/db.server';
// return type of this action
export type DeleteTaskActionData = {
formError?: string;
fieldErrors?: {
taskId?: string;
};
fields?: {
taskId?: string;
};
ok?: boolean;
};
const badRequest = (data: DeleteTaskActionData) => {
return json(data, { status: 400 });
};
export const action: ActionFunction = async ({ request }) => {
//setting values to fields from request
const form = await request.formData();
type fieldType = 'taskId';
const fieldList: fieldType[] = ['taskId'];
const fields = {} as Record<fieldType, string>;
for (const fieldName of fieldList) {
const fieldValue = form.get(fieldName) || '';
fields[fieldName] = fieldValue as string;
}
//validation
let fieldErrors = {} as Record<fieldType, string>;
if (!fields.taskId) {
fieldErrors.taskId = 'No Task Id provided';
return badRequest({ fieldErrors, fields });
}
//deleting task to database
try {
await db.task.delete({
where: {
id: fields.taskId,
},
});
} catch (err) {
return badRequest({
formError: err.message,
});
}
return redirect('/');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment