Search code examples
reactjstypescriptfetch-apies6-promise

Variables in array from fetch become zeros on return from function with promise


I have a function to get an array of some data from server:

async GetResolutionsAsync(signal: AbortSignal): Promise<BaseReference[]> {
    var resp = await fetch(`api/Improvements/GetResolutions`, {
        signal: signal
    })

    if (resp.status >= 400)
        throw new Error(`[ImprovementsDbHandler GetResolutionsAsync]: ${await resp.text()}`)

    const data = await resp.json() as BaseReference[]
    return data
}

My BaseReference type:

export type BaseReference = {
    id: number;
    name: string;
}

But I get 0 values in id variables after await resp.json()

(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 0, name: 'К реализации'}
1: {id: 0, name: 'На доработку'}
2: {id: 0, name: 'На перспективу'}
3: {id: 0, name: 'На рассмотрение ТС1'}
4: {id: 0, name: 'На рассмотрение ТС2'}
5: {id: 0, name: 'На рассмотрение ТС3'}
6: {id: 0, name: 'Отклонено'}
7: {id: 0, name: 'Не выбрано'}
length: 8

But the thing is, when I'm not putting data variable in return, everything works as intended. For example:

const data = await resp.json() as BaseReference[]

console.log(data)

return []

Console log:

(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: 'К реализации'}
1: {id: 2, name: 'На доработку'}
2: {id: 3, name: 'На перспективу'}
3: {id: 4, name: 'На рассмотрение ТС1'}
4: {id: 5, name: 'На рассмотрение ТС2'}
5: {id: 6, name: 'На рассмотрение ТС3'}
6: {id: 7, name: 'Отклонено'}
7: {id: 0, name: 'Не выбрано'}
length: 8

I have a lot of the same functions to get other arrays of data, but all of them return the requested values, what can be wrong here?


Solution

  • As the commentators said, somehow and somewhere the data is changing, I suppose, because I couldn't find the possibilities for these changes since the only thing I am doing with this array is setting it into state to use as certain dictionary. So now I am creating a copy of the array to put it to state, and the problem seems to be solved:

    iHandler.GetResolutionsAsync(controller.signal).then((resolutionsToSet) => {
        var newResolutions = JSON.parse(JSON.stringify(resolutionsToSet))
        setResolutions(newResolutions);
                                      
    }).catch((error) => { setLoading(false); errorHandler(error, "[GetResolutionsAsync]") })