'API returns undefined on refresh (redux toolkit, Twelve Data Api)

Currently working on a pet project that calls an API to generate forex pairs list after completing a similar code along and wanted to try to do it independently.

The code is working fine just yesterday and it is currently spitting out undefined type errors for data retrieved from the API call using redux toolkit. Still a newbie when it comes to this and would appreciate any help and guidance to solve this problem.

API used can be found here : https://rapidapi.com/twelvedata/api/twelve-data1/

Sorry if it became too lengthy, but the error occurs whenever I refresh the page. Currently I am working with just commenting the whole chunk of fxpairs.data.forEach in Forex.jsx to load the page, then uncommenting it to load a successful connection if that makes sense.

Here is the undefined error from developer console: enter image description here

This is my code for the api call in twelveDataApi.js(key omitted for obvious reasons):

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const twelveDataApiHeaders = { 
    'x-rapidapi-host': 'twelve-data1.p.rapidapi.com',
    'x-rapidapi-key': ''
}

const baseUrl = 'https://twelve-data1.p.rapidapi.com/';

const createRequest = (url) => ({ url, headers: twelveDataApiHeaders});

export const twelveDataApi = createApi({
    reducerPath: 'twelveDataApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getPairsList: builder.query({
            query: () => createRequest(`/forex_pairs`),
        }),
        getExchangeRate: builder.query({
            query: (symbol) => createRequest(`/exchange_rate?symbol=${symbol}`), //symbol has to be in the form USD/JPY
        })
    })
});

export const { 
    useGetPairsListQuery,
    useGetExchangeRateQuery,
} = twelveDataApi;

and here is Forex.jsx where error is occuring when fxpairs is used (omitted html since thats not the issue):

import { useGetPairsListQuery, useGetExchangeRateQuery } from '../services/twelveDataApi';

const Forex = () => {
    const symbol = 'USD/JPY';
    const { data: fxpairs, isFetching } = useGetPairsListQuery();

    console.log(fxpairs); 
    // pairs info manipulation 
    const otherPairs = [];
    const major = ['EUR/USD', 'USD/JPY', 'GBP/USD', 'USD/CHF', 'AUD/USD', 'USD/CAD', 'NZD/USD']; //major pairs to be placed on top 
    fxpairs.data.forEach(pair => { // <= this is where uncaught typeerror occured
        if (!major.includes(pair.symbol)) {
            otherPairs.push(pair.symbol);
        };
    });
    const allPairs = major.concat(otherPairs);
    const pairObj = {}; 
    allPairs.forEach(pair => { 
        pairObj[pair] = {};
        pairObj[pair]['symbol'] = pair;
        pairObj[pair]['from'] = pair.split("/")[0];
        pairObj[pair]['to'] = pair.split("/")[1];
    });

    // loading state
    if(isFetching) return "Loading...";



Solution 1:[1]

I have found the answer to be due to the location of isFetching statement.

Using the developer tool and a redux debugger, it can be seen that multiple API calls are being made and they are either rejected or left open. In order to check whether a an API call is still active, the isFetching statement is needed so any form of data manipulation after fetching should follow after the isFetching statement.

As such, I have shifted all API calls to the top, followed by the isFetching statement to check for open requests, before finally manipulating the data to suit my needs.

** editted for clarity

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1