1
votes

In my React app, I am using fetch to retrieve some chart data from server side. As shown in the following, the function fetchData is responsible for fetching the chart data in json format. I can see the call is successful in Chrome's network panel.

function fetchData () {
    let token;
    if (sessionStorage.bearerToken) {
        token = `Bearer ${sessionStorage.bearerToken}`;
    }
    console.log('the token is', token);
    const config = {};
    config.method = 'GET';
    config.headers = {
        'Content-Type':'application/json',
        'Authorization':token
    };
    const req = new Request(webConfig.ReqURL.fetchChartsData, config);
    // return fetch(`${config.base}dashboard_charts.json`)
    return fetch(req)
    .then((response) => {
        return response;
    });
}

function * getData (action) {
    try {
        // const charts = yield call(fetchData);
        const resp = yield apiCall(fetchData);
        const charts = resp.then((resp) => { return resp.json(); });
        console.log('the charts....', charts);
        yield put({ type: UPDATE_DASHBOARD_CHART, charts: charts });
    } catch (error) {
        yield put({ type: UPDATE_DASHBOARD_CHART, charts: [] });
    }
}

I need to add the http response status code checking. If the status code is 403 then I need to app to redirect to logon flow. That's why I am using apiCall(fetchData) instead of call(fetchData) directly.

export function* apiCall(fn, ...rest) {
    const response = yield call(fn, ...rest);
    const status = response.status;
    console.log('~~ status', status);
    if(status === 419) { //419: When the session has expired
        yield put(sessionExpired());
    }
    if(status === 403) { //403: When the resource is forbidden
        // yield put(resourceForbidden());
        yield auth();
        return Promise.reject(response);
    }
    if(status === 401) { //401: When the resource is unauthorized
        yield put(resourceUnauthorized());
    }

    return response;
}

The above code snippet is the implementation of apiCall in a Saga. It can trigger the auth flow if response code is 403 as expected.

But I am not sure how to handle the response for case 200. I can see that it returns a Promise, but in the getData function my console.log doesn't print anything (or say it's not executed).

May I know what the problem is in my code ?

1

1 Answers

0
votes

response.json() is a promise and should be handled with a then. The following code should work:

resp.then(resp => resp.json())
.then(json => {
    yield put({ type: UPDATE_DASHBOARD_CHART, charts: json });
});