Next.js Discord

Discord Forum

Data from Server Action fetch

Unanswered
Acorn-plum gall posted this in #help-forum
Open in Discord
Acorn-plum gallOP
action.ts
"use server";
export const joinServer = async (formData: FormData) => {
  const content = formData.get("topic");
  const response = await fetch("http://localhost/join", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ topic: content }),
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const data = await response.json();
  console.log(data);
  console.log(content);

  return data;
};

How can i recive this data in client component
client_component.tsx

import { joinServer } from "@/actions/actions";
const JoinChannel_Client = () => {
  const [inviteLink, setInviteLink] = useState<String>();
  return (
    <div>
      <form action={joinServer}>
        <Input
          type="text"
          name="topic"
          placeholder="Search Topic"
          className="px-4 py-2 mb-2"
          required
        />
        <input
          type="submit"
          className={buttonVariants({ variant: "default" })}
        />
      </form>
    </div>
  );
};

export default JoinChannel_Client;

28 Replies

Hi, I see a few confusions in your question, did you checkout the official Learn tutorial first? https://nextjs.org/learn
You may want to use the traditional data fetching mechanisme used in React
meaning useEffect + fetch
Acorn-plum gallOP
@Eric Burel thanks for reply, i know basic use of useEffect and ive gone through Nextjs learning page, i prefer learning by practice and asking question
so here since you are using a client component
you can call your server action using client-side js
onSubmit={async () => { const result = await yourAction() }
it's technically recommended to set up a React transition too but I haven't found clear documentation around that
you can use useFormStatus and useFormState too but in my understading, they are primarily meant to allow having the result within RSCs (these hooks are meant to work there, contrary to other hooks)
they fill a tad constrained when used in a client component
Acorn-plum gallOP
i can call server action from both client and server but the problem it get that reutrn data out of serverAction
tho useFormStatus or State
<form onSubmit={async () => { const result = await yourAction() }>
would this work for you ?
@Eric Burel would this work for you ?
Acorn-plum gallOP
const addTodo = async (formData: FormData) => {
    'use server';
    const supabaseUrl = 'YOUR_SUPABASE_URL';
    const supabaseKey = process.env.SUPABASE_KEY;
    const supabase = createClient( supabaseUrl, supabaseKey);
    const todoItem = formData.get('todo');
    if (!todoItem) {
      return;
    }
    // Save todo item to database
    const { data, error } = await supabase.from('todos').insert({
      todo: todoItem,
    });
  };

  return (
    <>
     <h2>Server Actions Demo</h2>
        <div>
          <form action={addTodo} method="POST">
            <div>
              <label htmlFor="todo">Todo</label>
              <div>
                <input id="todo" name="text" type="text"
                  placeholder="What needs to be done?"
                  required
                />
              </div>
            </div>
            <div>
              <button type="submit"> Add Todo</button>
            </div>
          </form>
        </div>
    </>
  );
}

in this example it saving data into a database so it can retrive in any component, but i just need to show value without database interaction
@Eric Burel before playing around with server actions, do you have a working version of this code, with client-side hooks and all?
Acorn-plum gallOP
yes in my previous implemention i used basic hooks and onSubmit to make request in client side
looks like i need to look into context api and save data into later recive in other component
Acorn-plum gallOP
@Eric Burel
<form
        action={async (formData) => {
          console.log(formData);
          const data = await joinServer(formData);
          setInviteLink(data);
        }}
      ></Form>

this what i was looking for
i didnt know async can be used this way in action
cool, I would have used "onSubmit" I didn't remember tht action could accept a function