Skip to content

Instantly share code, notes, and snippets.

@azu
Last active May 30, 2024 12:44
Show Gist options
  • Save azu/1f940bb723fe05dc224562615765a681 to your computer and use it in GitHub Desktop.
Save azu/1f940bb723fe05dc224562615765a681 to your computer and use it in GitHub Desktop.
import React, { useActionState } from "react";
const validate = _ => {};
const isValidationError = _ => {};
const isNetworkError = _ => {};
const DisplayError = ({
error,
}: {
error: ReturnType<typeof usePage>["error"];
}) => {
if(isValidationError(error)) {
return <>Validation Error</>
} else if(isNetworkError(error)) {
return <>Network Error</>
}
// unhandled error will be compile error.
console.error("unknown erro", error satisfies never);
};
export const usePage = () => {
const [error, handleSubmit, loading] = useActionState(
async (prevState: unknown, value: string) => {
const result = validate(value);
if(!result.ok) {
return result.error;
}
// do somthing
try {
const respose = await fetch("https://...", { method: "post", body: JSON.stringify(result.value) });
if(!response.ok) {
return new BadRequestError();
}
const json = await response.json():
} catch (error) {
return new NetworkError();
}
},
null,
);
return {
handleSubmit,
loading,
error,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment