Skip to main content

Server Actions Introduction

What are Server Actions?

Why use Server Actions?

How to use Server Actions

Example

Here is an example of a server action:

export async function getUserProfile() {
try {
const session = await getSession();
const uid = ObjectId.createFromHexString(session.user.sub.substring(6));
const db = await connectDB();
const user = await User.findOne({ _id: uid });
return JSON.parse(JSON.stringify(user));
} catch (error) {
console.error("getUserProfile:", error);
Error(error);
}
}

And one way to use it in a component:

import { getUserProfile } from "../server-actions";

export default function Account() {
const [userDoc, setUserDoc] = useState(null);

useEffect(() => {
try {
getUserProfile().then((data) => {
setUserDoc(data);
});
} catch (error) {
console.error("Error fetching user data:", error);
}
}, []);

return (
<>
<h1><b>{userDoc?.first_name} {userDoc?.last_name_initial}</b></h1>
<p>{userDoc?.email}</p>
</>
);
}