Fetch data from form submission action
Answered
Morelet’s Crocodile posted this in #help-forum
Morelet’s CrocodileOP
Hey there, I am new to nextJs 14. I want to fetch the data on the first render and then on form submit with the search query. I want to display the data from the action if it was triggered. How can I do it, without fetching inside a client component?
Thanks a lot!
export default async function Home() {
const books = await getBooks();
const searchBook = async (formData: FormData) => {
"use server";
const bookName = formData.get("bookName");
const fetchData = await getBooks(bookName as string);
};
return (
<div className="text-red-500">
<form action={searchBook}>
<input
type="text"
name="bookName"
placeholder="Search..."
/>
<button onClick={() => {}}>Search</button>
</form>
{books.map((book: Book) => (
<BookItem book={book} key={book.id} />
))}
</div>
);
}
Thanks a lot!
export default async function Home() {
const books = await getBooks();
const searchBook = async (formData: FormData) => {
"use server";
const bookName = formData.get("bookName");
const fetchData = await getBooks(bookName as string);
};
return (
<div className="text-red-500">
<form action={searchBook}>
<input
type="text"
name="bookName"
placeholder="Search..."
/>
<button onClick={() => {}}>Search</button>
</form>
{books.map((book: Book) => (
<BookItem book={book} key={book.id} />
))}
</div>
);
}
Answered by Ray
export default async function Home({searchParams}: {searchParams: {[k:string]: string}}) {
const books = await getBooks(searchParams.get('bookName'));
return (
<div className="text-red-500">
<form>
<input
type="text"
name="bookName"
placeholder="Search..."
/>
<button>Search</button>
</form>
{books.map((book: Book) => (
<BookItem book={book} key={book.id} />
))}
</div>
);
}2 Replies
Shy Albatross
if
or
return the data from the action and use
but overall form actions are for mutations, and a search is just a GET, so you're misusing server actions here IMO
getBooks makes a fetch, yo ucan tag that fetch and revalidateTag in the actionor
return the data from the action and use
useFormState to access itbut overall form actions are for mutations, and a search is just a GET, so you're misusing server actions here IMO
export default async function Home({searchParams}: {searchParams: {[k:string]: string}}) {
const books = await getBooks(searchParams.get('bookName'));
return (
<div className="text-red-500">
<form>
<input
type="text"
name="bookName"
placeholder="Search..."
/>
<button>Search</button>
</form>
{books.map((book: Book) => (
<BookItem book={book} key={book.id} />
))}
</div>
);
}Answer