Is it silly to POST to a server action to get redirected to another URL?
Unanswered
Florian posted this in #help-forum
FlorianOP
I have this (simplified) filter form in my app. It's a server component that makes a POST request to a server action, which then applies URL search params and redirects to updated URL.
2 Replies
FlorianOP
async function handleSearch(formData: FormData) {
"use server";
const values = Object.fromEntries(formData.entries());
const { query, category, maxPrice, zipcode } =
advertisementFilterSchema.parse(values);
const searchParams = new
...(query && { query }),
...(category && { category }),
...(maxPrice && { maxPrice }),
...(zipcode && { zipcode }),
});
redirect(`/?${searchParams.toString()}`);
}
interface FilterBarProps {
defaultValues: FilterValues;
}
export default function FilterBar({ defaultValues }: FilterBarProps) {
return (
<div>
<p>Filter results</p>
<form action={handleSearch}>
<Input
name="query"
type="search"
placeholder="What are you looking for?"
defaultValue={defaultValues.query}
/>
<Input
name="zipcode"
type="text"
placeholder="Zipcode"
defaultValue={defaultValues.zipcode}
/>
<div className="relative">
<select
name="category"
defaultValue={defaultValues.category || "all"}
>
<option value="all">All categories</option>
{categories.map((category) => (
<option key={category} value={category}>
{category}
</option>
))}
</select>
</div>
<Input
name="maxPrice"
type="text"
placeholder="Max price"
defaultValue={defaultValues.maxPrice}
/>
// This uses useFormStatus to show a loading indicator
<FormSubmitButton>
<Search size={20} /> Find
</FormSubmitButton>
</form>
</div>
);
}Instead of the server action, I could also use
However, I like the server action approach because it allows me to trim away unused search params (the GET approach leaves them in the URL with empty values).
It seems that, when JavaScript is enabled, the server action gets the updated page as a response to the post request. Meaning that it's effectively still a single request, which would make my approach valid. Is my understanding correct?
However, when JavaScript is disabled, it seems to make two separate requests (get and post).
method="GET" in the form and skip the POST request altogether.However, I like the server action approach because it allows me to trim away unused search params (the GET approach leaves them in the URL with empty values).
It seems that, when JavaScript is enabled, the server action gets the updated page as a response to the post request. Meaning that it's effectively still a single request, which would make my approach valid. Is my understanding correct?
However, when JavaScript is disabled, it seems to make two separate requests (get and post).