server side action inside client component
Unanswered
Brown bear posted this in #help-forum
Brown bearOP
Hello, how can i use a server side action (POST) inside a form that i need it to be client so i can send toast when success on front or error, how can i manage that errors in frontend?
7 Replies
Brown bearOP
"use client"
import { craftItem } from "@/lib/actions/user.actions"
import { SubmitButton } from "../SubmitButton/SubmitButton"
interface CraftingFormProps {
clerkId: string
value: string;
}
const CraftingForm = ({ clerkId, value }: CraftingFormProps) => {
const handleAction = async (formData: FormData) => {
const itemToCraftName = formData.get("name") as string;
await craftItem(clerkId, itemToCraftName);
}
return (
<form action={handleAction}>
<input
name="name"
type="text"
value={value}
readOnly
min="1"
className="bg-transparent"
/>
<SubmitButton label="Craftear" labelLoading="Crafteando..." />
</form>
)
}
export default CraftingForm;im trying to execute this code on client side executing that action that will do this:
export const craftItem = async (userId: string, itemToCraftName: string) => {
try {
await connectToDB();
const user = await User.findOne({ clerkId: userId });
if (!user) {
return NextResponse.json({ message: 'Usuario no encontrado' }, { status: 400 });
}
const inventory = await Inventory.findOne({ characterId: user._id });
if (!inventory) {
return NextResponse.json({ message: 'Inventario no encontrado para este usuario' }, { status: 400 });
}
const itemToCraft = await Item.findOne({ name: itemToCraftName });
if (!itemToCraft) {
return NextResponse.json({ message: 'Ítem no encontrado' }, { status: 400 });
}
const itemsRequired = itemToCraft.itemsRequired;
const itemsInInventory = inventory.items;
for (let itemRequired of itemsRequired) {
const existingItemIndex: number = itemsInInventory.findIndex((inventoryItem: any) => inventoryItem.item.equals(itemRequired.item));
if (existingItemIndex !== -1) {
const existingItem = itemsInInventory[existingItemIndex];
if (existingItem.quantity > itemRequired.quantity) {
existingItem.quantity -= itemRequired.quantity;
console.log(`Se ha usado ${itemRequired.quantity} de ${existingItem.item}`)
} else {
itemsInInventory.splice(existingItemIndex, 1);
console.log('Item removido', existingItem.item)
}
await inventory.save();
} else {
return NextResponse.json({ message: 'No tienes los ítems necesarios para craftear este ítem' }, { status: 400 });
}
}P1
const item = {
item: itemToCraft._id,
quantity: 1,
}
inventory.items.push(item);
await inventory.save();
return NextResponse.json("Ítem crafteado exitosamente!", { status: 200 });
} catch (error) {
console.error('Error crafting item:', error);
return new Response('Error crafting item', { status: 500 });
}
}P2
that's the action
inside /action/user.action.ts that is a "use server" file
how can i send success toast or error in case error in the front when action in server side?