I'm working with a Next JS new Data Fetching feature to load data from an API and assigns it to a variable called 'contact.' However, I'm encountering the error message "variable 'contact' is used before being assigned."
I want to ensure that I handle this situation correctly and prevent the error from occurring. How can I properly structure my server action to load data from the API and assign it to 'contact' so that the error is resolved, and I can work with the data as expected?
export default async function Page() {
let contact: Contact
try {
[contact] = await getContact(104);
} catch (e: FetchError) {
console.log(e.message)
}
......
<EditContactForm contact={contact}/> <-- Variable is used before being assigned
Edit What works is if I retrieve the data as follows:
const [contact] = await getContact(104).catch((err) => {
console.log(err.message)
}) || []
But I prefer to use try-catch statement, so how can I convert it?
The TS is thinking that it isn't necessary for the
contact
to have a value when it is being used.Just add a guard:
This will make sure that the
EditContactForm
is rendered only when thecontact
is defined.