deagleshot32
deagleshot32

Reputation: 111

Fetching Data using RTK-query Redux

I setup my Redux like this

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

const baseUrl = 'http://localhost:6969/api/coins';
const createRequest = (url) => ({ url });

export const coinApi = createApi({
  reducerPath: 'coinApi',
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCoins: builder.query({
      query: () => createRequest(`/watchlist`),
    }),
  }),
});

export const { useGetCoinsQuery } = coinApi;

import { configureStore } from '@reduxjs/toolkit';
import { coinApi } from '../../src/services/coinApi';
import { setupListeners } from '@reduxjs/toolkit/query';

export const store = configureStore({
  reducer: {
    [coinApi.reducerPath]: coinApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(coinApi.middleware),
});

setupListeners(store.dispatch);

and in my component I am rendering the data in JSX by this

const CoinList = () => {
const { data, isFetching } = useGetCoinsQuery();
console.log(data);

When I console.log(data) it shows me the correct data however when I map in JSX, it gives me a type error of: Cannot read properties of undefined (reading 'map')

Am I suppose to give data a Typescript of if it exists? Why is data undefined when the console.log is correct?

Upvotes: 0

Views: 884

Answers (2)

samcesa45
samcesa45

Reputation: 27

Initialize data = [ ] const {data = [ ] ,isFetching} = useGetCoinsQuery()

check this https://redux-toolkit.js.org/tutorials/rtk-query

Upvotes: 0

deagleshot32
deagleshot32

Reputation: 111

Ah. I just figured out then I must add

if (isFetching) return 'Loading ...'

or else data is still undefined since its not fetched yet? Not sure but this was the fix.

Upvotes: 1

Related Questions