Last active
May 30, 2024 12:44
-
-
Save azu/1f940bb723fe05dc224562615765a681 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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