How to properly type guard to avoid "possibly undefined" #181
-
Hi But in the template each time I use the data it still can be undefined Like here, I want to use a mutation, so I need to pass the reservation value, but it can be undefined : If I put the if (reservation.value) {
const {isLoading: isUpdating, isSuccess: isUpdated, mutate, reset} = useMutationUpdateReservation(reservation.value)
} then The only way I found for now is to force the type of |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I added more precision to the question 👍 |
Beta Was this translation helpful? Give feedback.
-
So the typing is good, since on first render you might actually get undefined. This might also be true for the click handler, cause request to server might get stuck, or fail. In summary, types are hinting you that you might encounter an undefined value here, which might be caused by poor network connection, which is correct. You should definitely guard against that scenario. |
Beta Was this translation helpful? Give feedback.
-
So if you wondering what the actual code looks like : const reservation = ref<Reservation>({
id: 0,
statut: {
label: 'Non traitée',
value: 'non_traitee'
},
date_du_rendez_vous_souhaitee: '',
validation_du_rendez_vous: {
}
}) Then when the actual data is retrieved from the query I replace the default value by the actual data. So const { isLoading: isReservationLoading, isIdle: isReservationIdle, isError: isReservationError, data: reservationAPI, error, isFetching, refetch: reservationRefetch } = useQueryGetReservationById(reservationId, {
cacheTime: 0,
refetchOnWindowFocus: false,
onSuccess: (data) => reservation.value = data,
onError(error) {
if (error && error instanceof ApiError) {
router.push({name: 'NotFound'}).then(() => Swal.fire('Une erreur est survenue', error.message, 'error'))
} else {
router.push({name: 'NotFound'}).then(() => Swal.fire('Une erreur est survenue', undefined, 'error'))
}
}
}) Here is the where I check if export async function updateReservation(reser: Reservation) {
if (reser && reser.id !== 0) {
let req = await instanceAxios.patch<number>(`${reser.id}`, reser)
handleResponseError(req.data)
return req.data
} else {
throw new Error('La réservation reçu est vide')
}
} I'm unsure if the way that I've done it is a good way to do it, so feel free to tell me if you see something wrong/bad |
Beta Was this translation helpful? Give feedback.
So the typing is good, since on first render you might actually get undefined. This might also be true for the click handler, cause request to server might get stuck, or fail.
Therefore you need to guard against that kind of value. If it's undefined , you might want to provide some fallback value, or even some error page.
When you are sure that the value would be there (you should not, cause you user might have a crappy network connection from his mobile phone) you might overwrite it with typescript assertion. But i think you should be more defensive and provide a fallback when the value would not be there as you are anticipating.
As for your custom hook, you might want to provide there a…