amanda nascimento
amanda nascimento

Reputation: 5

UseSelector returns undefined

this peace of code sould watch the state of a cart containing a bunch of bets made by the user

const { games } = useSelector((state: any) => state.cart) whitch i pass to another component like this

<AppRecentUserGame games={games} filter={gameChoice} />

at the homepage it should receive this games const and then render that bets list filter by type or not

interface AppRecentUserGameProps {
  games: Bet[];
  filter: GameTypes;
}

export const AppRecentUserGame = ({
  games,
  filter
}: AppRecentUserGameProps) => {
  const [filterGame, setFilterGame] = useState("");
  useEffect(() => {
    setFilterGame(filter.type);
  }, [filter]);

  const filteredGames = () => {
    if (filterGame === "") {
      return !!games.length ? (
        games.map((game: any) => (
          <CartItem key={game.id} color={game.color}>
            <p>{formatNumberInArray(game.gameNumbers)}</p>
            <div>
              <p>
                {dateFormatValue(new Date(game.betDate))} - (
                {priceFormatted(game.price)})
              </p>
            </div>
            <strong>{game.type}</strong>
          </CartItem>
        ))
      ) : (
        <EmptyContainer>
          <EmptyCart />
        </EmptyContainer>
      );
    } else if (games && filter) {
      const filterGame = games.filter((game) => game.type === filter.type);
      return filterGame.map((game: any) => (
        <CartItem key={game.id} color={game.color}>
          <p>{formatNumberInArray(game.gameNumbers)}</p>
          <div>
            <p>
              {dateFormatValue(new Date(game.betDate))} - (
              {priceFormatted(game.price)})
            </p>
          </div>
          <strong>{game.type}</strong>
        </CartItem>
      ));
    }
  };

  return <>{filteredGames()}</>;
};

whenever a user save the bets he made, tha group os bets must populate the cartSlice, witch later all will use to show the user that list of bets he made in tha homepage here is how i handle the save process

const [cartsGames, setCartGames] = useState<Bet[]>([])  
const saveGame = () => {
    try {
      if (totalPrice < 30) {
        const minPrice = gameType["min-cart-value"] 
        throw new Error(
          `Adicione pelo menos ${priceFormatted(minPrice)} em Apostas`)
      }
      cartsGames.forEach((game) => {
        dispatch(CartActions.addToCart(game)) 
        console.log(game)
      }) 
      setCartGames([]) 
      setMessageToUser({
        description: "Aposta Feita, Boa Sorte!",
        color: "var(--spinner)",
        active: true,
      }) 
      setRedirect(true) 
    } catch (error) {
      setMessageToUser({
        description: error.message,
        color: "var(--blue)",
        active: true,
      }) 
    }
  } 

here is my store

import { configureStore } from "@reduxjs/toolkit";
import { cartSlice } from "./cartSlc";
import { userSlice } from "./userSlc";
export const store = configureStore({
  reducer: {
    user: userSlice.reducer,
    cart: cartSlice.reducer
  },
}); 

the userSlice:


import { SignedUpUserProps } from "../types/userSignup";

const initialState: SignedUpUserProps = {
  users: [
    {
      id: "1",
      name: "test",
      email: "[email protected]",
      password: "123456789",
      recentGames: [],
    },

  ],
  isLogged: false,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: { // actions
    createUser(state, action) {
      const newUser = action.payload;
      state.users.push(newUser);
    },
    logIn(state) {
      state.isLogged = true;
    },
    logOut(state) {
      state.isLogged = false;
    },
    saveInRecentGames(state, action) {
      const users = [...state.users];
      const user = users.find((user) => user.id === action.payload.id);
      if (user) {
        const prevState: any = [...user.recentGames];
        user.recentGames.push(prevState, ...action.payload.games);
      }
    },
  },
});

const UserActions = userSlice.actions;
export { userSlice, UserActions };

the cart slice

import { createSlice } from "@reduxjs/toolkit";
import { Cart } from "../types/cart";


const initialState: Cart = {
 game: [],
 totalPrice: 0,
};

const cartSlice = createSlice({
 name: "cart",
 initialState,
 reducers: {
   addToCart(state, action) {
     const newBet = action.payload
     state.game.push(newBet)
     state.totalPrice = state.totalPrice + newBet.price
   },
 },
})
const CartActions = cartSlice.actions
export { cartSlice, CartActions }

Upvotes: 0

Views: 125

Answers (1)

Delice
Delice

Reputation: 856

You select your state games with an "s" but when I look at your slice it is named without the "s".

const { games } = useSelector((state: any) => state.cart)

const initialState: Cart = { game: [], totalPrice: 0, };

Upvotes: 2

Related Questions