4

I keep getting this same error of undefined data for multiple components in my data, it was working fine but for some reason it stops in fetching data and starts giving undefined out of the blue.

this is my store.js

import {configureStore, getDefaultMiddleware} from '@reduxjs/toolkit'
import { cryptoApi} from '../services/cryptoAPI';
import { cryptoNewsApi } from '../services/cryptoNewsApi';

export default configureStore({
    reducer: {
        [cryptoApi.reducerPath]: cryptoApi.reducer,
        [cryptoNewsApi.reducerPath]: cryptoNewsApi.reducer,
    },
    middleware: (getDefaultMiddleware) => 
    getDefaultMiddleware().concat(cryptoNewsApi.middleware, cryptoApi.middleware)
});

Api file

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

const cryptoApiHeaders = {
'HEADERS1',
'HEADERS2',
'HEADERS3',
} // replaced the actual headers for question ;p

const baseUrl = "https://coinranking1.p.rapidapi.com/"

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


export const cryptoApi = createApi({

  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({baseUrl}),
  endpoints: (builder) =>({
    getCryptos: builder.query({
      query: () => createRequest('/coins'),
    })
  })
})

export const {  useGetCryptosQuery  } = cryptoApi;

This is my App.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import {Provider} from 'react-redux';
import {BrowserRouter} from 'react-router-dom'
import './index.scss';
import App from './App';
import store from './app/store';
const root = ReactDOM.createRoot(
  document.getElementById('root') 
);
root.render(
  <BrowserRouter>
  <Provider store = {store}>
    <App />
  </Provider>
  </BrowserRouter>
);

This is how i am trying to fetch the data

import { useGetCryptosQuery } from '../../services/cryptoAPI';

  const {data, isLoading, isFetching,error,isSuccess} = useGetCryptosQuery();
  const coinData = data?.data
  //When trying to access this globalStats, we get an error of undefined. 

again, this was working fine and i made no changes to the code but now it seems to be giving undefined error. i have used isLoading, isFetching and isSuccess in each component giving the error as such:

if (isLoading && isFetching) return <>Loading....</>
if(error) {console.log(error)}

i tried using JSON server as well and made sure the data request is coming in: Data Coming in Response , the image of the error: Error

UPDATE: the error seems to be while importing data :

const {data, isLoading: isLoadingCoins} = useGetCryptosQuery();

i switched it between json server from local machine and a rapid api server but both were giving undefined. i have tried going through the rtk query but seems like im looking in the wrong place here. this is data getting in using rapid api: rapidApi 200 Success

link to code: https://github.com/Raghav-rv28/crypto-metrics

Raghav
  • 41
  • 1
  • 5

5 Answers5

1

I had this error and managed to solve this you need to add middleware in the store.js after the reducer and it will work...like this

import { configureStore, } from "@reduxjs/toolkit";
import { cryptoApi } from "../services/Cryptoapi";

export default configureStore({
    reducer: {
        [cryptoApi.reducerPath]:cryptoApi.reducer,
     
    },
    middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(cryptoApi.middleware),
})
0

You have a typo there - the variable is called coinsData, but you want to access coinData.

phry
  • 35,762
  • 5
  • 67
  • 81
  • i have changed the name but still the same error, its not a typo issue because all components start giving this error if run them all. in rare few cases the website starts running but all data is undefined. – Raghav Apr 18 '22 at 18:35
  • Continuing with the snippet above: Why are you accessing `cryptoList?.data?.coins` when your data is in the `data` variable, declared directly above? I see no reason for `cryptoList` anywhere there – phry Apr 18 '22 at 19:44
  • i didnt update the question properly, but no i made a typo in the question, in actual code which is on github, it is data not cryptolist – Raghav Apr 18 '22 at 20:16
  • that github link leads to a project without any commits after the initial project setup – phry Apr 18 '22 at 20:44
  • https://github.com/Raghav-rv28/crypto-metrics/tree/main – Raghav Apr 18 '22 at 20:45
  • Thank you so much @phry for your help, but i figured out the answer. the rapidApi stopped giving certain data in their query and that was the reason when i went through the queries. sorry to waste your time :p cheers. – Raghav Apr 18 '22 at 22:53
0

I guess I understand you are not subscribed to this API in Rapidapi so thought you can get another free API.

and don't using again

const {data, isLoading, isFetching,error,isSuccess} = useGetCryptosQuery();
  const coinData = data?.data

It is enough to use it like this

   import { useGetCryptosQuery } from '../../services/cryptoAPI';
    
      const {data: coinData, isLoading, isFetching,error,isSuccess} = useGetCryptosQuery();
      const [coin, setCoin] = useState(coinData);
      //now can been access to stats.
  • i am still learning react so i am having trouble with Async JS, which is why i was not using state, i tried a combination of useState and useEffect but ended up having calamities of error brought upon myself. the project is working now, its like everything is held up by bobby pins and staples :p – Raghav Apr 22 '22 at 15:20
0

I was facing the exact issue. This is how I resolved it. If you know/found any other solution please let me know. Also, if you know understand the logic/reason behind this error, please explain it to me.

const {data: cryptosList, isFetching} = useGetCryptosQuery()
  const [cryptos,setCryptos] = useState(cryptosList?.data?.coins)

  useEffect(()=>{
    if(!isFetching){
    setCryptos(cryptosList?.data?.coins)
  }
  },[isFetching])
  • I typed up the exact code above and it works, until I refresh the page and it crashes again with the following error: Uncaught Error: Warning: Middleware for RTK-Query API at reducerPath "cryptoApi" .... everything is fine until the page refresh – Da Moose Jan 13 '23 at 08:05
-2

I guess your baseQuery is not set correctly, now you have:

 baseQuery: fetchBaseQuery({baseUrl}),

It should be:

 baseQuery: fetchBaseQuery({baseUrl: baseUrl}),