DrMister DrMister - 1 month ago 8
React JSX Question

Why does flow make me check for an undefined value that is already defined?

In the following code flow throws an error if I don't check for the existence of

response
. But the
const response
definition should guarantee that response is available. Why does flow not accept omitting the check for the existence of
response
?

/* @flow */

// ... import dependencies

export function* loadDepartments(): Generator<*, *, *> {
try {
const response = yield call(getJson, endpoints.departments);
if (response && typeof response.data !== 'undefined') {
yield put(actions.loadingDepartmentsSucceeded(response.data));
}
} catch (errors) {
yield put(actions.loadingDepartmentsFailed(errors));
}
}

Answer

Event if you used const, the value of response can be undefined, depending on what your call function yields. A variable defined with const can indeed contain the value undefined.

In case response is undefined, then the check

if (typeof response.data !== 'undefined') {

would raise a TypeError because you can't read property "data" of undefined.