Next.js Discord

Discord Forum

Server Actions question

Unanswered
Palomino posted this in #help-forum
Open in Discord
PalominoOP
I'm querying an external API in a server action after a form submission, but how do I display the returned results from that API on the page?

Server action:
'use server' import { revalidatePath } from 'next/cache'; export async function searchMusic(formData) { if (!formData) { return null } const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'airwave/1.0.0 (https://airwave.com)' } const res = await fetch(${process.env.MUSICBRAINZ_API_URL}/release?query=artist:"${formData.get('artist')}"ANDtitle:"${formData.get('song')}"&limit=5, { // const res = await fetch(${process.env.MUSICBRAINZ_API_URL}/release?query=artist:"${formData.get('name')}"ANDtitle:"yes"&limit=5, { cache: 'no-store', headers: headers }) const result = await res.json(); console.log(result) revalidatePath("/music/add") return result }

On the page I have a form with 2 inputs which pass the 'artist' and 'song' fields and below I'm trying to map the results. I'm calling the action into the page with
const searchResults = await searchMusic();
but searchReults is always empty

5 Replies

From the docs:
The arguments and return value of Server Actions must be serializable by React.

You can find a list of serializable arguments and values here: https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
PalominoOP
Thanks - I've tried the example on that page but I still can't get it to work. Any code help or links to examples would be appreciated. Only other way I can think of to do it is to collect the values of the inputs then send the url of the api to the server action as a prop and consume the results that way
Can you show what you tried doing from that example?
PalominoOP
I implemented this another way with useEffect and props but thanks 👍🏻
Glad to hear you managed to do it ✌🏻