score:1

Accepted answer

inside your fetchutil function, it ends with no return value, which means your fetchutil function is going to implicitly return undefined.

you said

fetch(`${process.env.react_app_api}${url}`, request)
    .then(response => {
        if(response.ok) {
            return response.json()
        } else if(response.status === 401) {
            refreshtoken().then(() => retryfn())
        } else {
            console.error(`error on fetching data from api: ${response.status}, ${response.text}`)
        }
    })
    .then(json => {
        console.log(json) // (1) 
        return json
    })
    .catch(error => console.error(error))

inside this function, (1) part works well, right?

i think if you change your code like below it would work.

first, update your fetchutil code like this. return fetch.

const fetchutil = (url, requestmethod, requestbody, retryfn) => {
    // block thread if the token needs to be refetched
    if(sessionstorage.getitem('token') == null || number(sessionstorage.getitem('token_expiration')) < new date().gettime()) {
        refreshtoken()
    }        

    let request = {
        method: requestmethod,
        headers: {
            'authorization': `bearer ${sessionstorage.getitem('token')}`,
            'content-type': 'application/json'
        }
    }
    if(requestmethod === 'post' || requestmethod === 'put') {
        request.body = json.stringify(requestbody)
    }

    // return fetch here! it will return a promise object. 
    return fetch(`${process.env.react_app_api}${url}`, request)
    .then(response => {
        if(response.ok) {
            return response.json()
        } else if(response.status === 401) {
            refreshtoken().then(() => retryfn())
        } else {
            console.error(`error on fetching data from api: ${response.status}, ${response.text}`)
        }
    })
    .then(json => {
        console.log(json)
        return json
    })
    .catch(error => console.error(error))
}

second, update your getchargehistory like this.

const getchargehistory = async (installationid) => {
    const result =  await fetchutil(`/chargehistory?options.installationid=${installationid}`, 'get', {}, getchargehistory)
    console.log(result);
}

because i don't have full access to your code, there still might be errors left, but i hope this helps!


Related Query

More Query from same tag