0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.