how to handle responses from the server on the client?

I'm trying to implement server side auth with a cookie, the cookie part it's working, but the thing is I want to save my user info - that is returned by the login function (name, avatar, etc) - in a context in order to use it across the app. How do I go about handling the response on the client in order to properly set it in the context ?
1 Reply
gmnss1917
gmnss191711mo ago
const [loggingIn, logIn] = createServerAction$(
async (form: FormData, { locals }) => {
return await logInFn(form, locals);
}
const [loggingIn, logIn] = createServerAction$(
async (form: FormData, { locals }) => {
return await logInFn(form, locals);
}
export async function logInFn(
form: FormData,
locals: Record<string, any>
): Promise<User | undefined> {
const pb = getPb(locals);
try {
const { record } = await pb
.collection("users")
.authWithPassword<User>(
form.get("username") as string,
form.get("password") as string
);
const user: User = {
id: record.id,
username: record.username,
name: record.name,
email: record.email,
avatar: record.avatar,
};
return user;
} catch (error) {
if (error instanceof ClientResponseError) {
console.error("ERROR: ", error);
throw new ServerError("Failed to authenticate", {
status: (error as ClientResponseError).status,
});
}
}
}
export async function logInFn(
form: FormData,
locals: Record<string, any>
): Promise<User | undefined> {
const pb = getPb(locals);
try {
const { record } = await pb
.collection("users")
.authWithPassword<User>(
form.get("username") as string,
form.get("password") as string
);
const user: User = {
id: record.id,
username: record.username,
name: record.name,
email: record.email,
avatar: record.avatar,
};
return user;
} catch (error) {
if (error instanceof ClientResponseError) {
console.error("ERROR: ", error);
throw new ServerError("Failed to authenticate", {
status: (error as ClientResponseError).status,
});
}
}
}