Server action giving "Functions cannot be passed directly to Client Components" error with forEach
Answered
Cape lion posted this in #help-forum
Cape lionOP
Hi
I'm trying to use the new Server Actions to process some form data, but as soon as I use a loop in the function, I get an error that "Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server"".
Here's the basic code of my component:
I'm trying to use the new Server Actions to process some form data, but as soon as I use a loop in the function, I get an error that "Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server"".
Here's the basic code of my component:
export default async function Home() {
const items = await getData(); // fetch available items from Airtable
async function create(formData: FormData) {
'use server'
wines.forEach((item) => {
const count = formData.get(`${item.id}.count`);
console.log(count);
});
}
return (
<form action={create}>
{items.map((item) => (
<p key={item.id}>
<label>{item.name}</label>
<input type="number" name={`${item.id}.count`}/>
</p>
))}
<button type="submit">Order</button>
</form>
);
}Answered by Cape lion
@aardani found the issue: it's because I was reusing the
items variable from the component scope, which doesn't exist in the actual server action.14 Replies
does it work without the .map?
Cape lionOP
@aardani yeah, if I just do
console.log(formData), I get an outputit's like the callback function of the forEach messes it up
whats the error code?
Cape lionOP
I don't see an exact error code, this is the error page
Create a minimal reproducible repository, maybe i can take a look at it
Cape lionOP
Was trying to create a codesandbox, but getting a different error there >_>
yeah codesandbox is broken with next.js (for now?)
Cape lionOP
dang
Cape lionOP
@aardani found the issue: it's because I was reusing the
items variable from the component scope, which doesn't exist in the actual server action.Answer
Cape lionOP
redeclaring it fixes it
super unclear error
dang i missed that too