简体   繁体   中英

React | Redux Toolkit Shared State Undefined

I am creating a simple app to play with Redux ToolKit along react; however, I can see the object in the redux chrome tab, but unable to access it through components using react hooks.

My slice:

 import {
  createSlice,
  createSelector,
  createAsyncThunk,
} from "@reduxjs/toolkit";

const initialState = {
  cryptoList: [],
  loading: false,
  hasErrors: false,
};

export const getCryptos = createAsyncThunk("cryptos/get", async (thunkAPI) => {
  try {
    const cryptosUrl =
      "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd";
    let response = await fetch(cryptosUrl);
    console.log(response);
    return await response.json();
  } catch (error) {
    console.log(error);
  }
});

const cryptoSlice = createSlice({
  name: "cryptos",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getCryptos.pending, (state) => {
      state.loading = true;
    });
    builder.addCase(getCryptos.fulfilled, (state, { payload }) => {
      state.loading = false;
      state.cryptoList = payload;
    });
    builder.addCase(getCryptos.rejected, (state, action) => {
      state.loading = false;
      state.hasErrors = action.error.message;
    });
  },
});

export const selectCryptos = createSelector(
  (state) => ({
    cryptoList: state.cryptoList,
    loading: state.loading,
  }),
  (state) => state
);

export default cryptoSlice;

My component:

import React, { useEffect } from "react";
import { getCryptos, selectCryptos } from "./cryptoSlice";
import { useSelector, useDispatch } from "react-redux";

const CryptoComponent = () => {
  const dispatch = useDispatch();
  const { cryptoList, loading, hasErrors } = useSelector(selectCryptos);

  useEffect(() => {
    dispatch(getCryptos());
  }, [dispatch]);

  const renderCrypto = () => {
    if (loading) return <p>Loading Crypto...</p>;
    if (hasErrors) return <p>Error loading news...</p>;

    if (cryptoList) {
      return cryptoList.data.map((crypto) => <p> {crypto.id}</p>);
    }
  };

  return (
    <div className="container">
      <div className="row">CryptoComponent: {renderCrypto()}</div>
    </div>
  );
};

export default CryptoComponent;

All constructed values from the state: cryptoList, loading, hasErrors, seem to be undefined at the component level.

Any suggestions are appreciated!

Have you tried using the following createSelector code:

 export const selectCryptos = createSelector(
    (state) => state, 
    (state) => ({
     cryptoList: state.cryptoList,
     loading: state.loading,
    })
 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM