'usedispatch or useselector is not working

the basket no is not increasing on pressing add to basket

header.js

import Image from "next/image";
import { 
    MenuIcon,
    SearchIcon,
    ShoppingCartIcon,
   } from "@heroicons/react/outline";
import { signIn, signOut, useSession} from "next-auth/react";
import { useRouter } from "next/router";
import { useSelector } from "react-redux";
import { selectItems } from "../slices/basketSlice";


function Header() {
  const { data: session } = useSession();
  const router = useRouter();
  const items = useSelector(selectItems);

  return (
    <header>
       <div className="flex items-center bg-amazon_blue p-1 flex-grow py-2">
         <div className="mt-2 flex items-center flex-grow sm:flex-grow-0">
          <Image
          onClick={() => router.push('/')} 
            src='https://links.papareact.com/f90'
            width={150}
            height={40}
            objectFit="contain"
            className="cursor-pointer"
          />
         </div>
         {/*search bar*/}
         <div className="hidden sm:flex items-center h-10 rounded-md flex-grow cursor-pointer bg-yellow-400 hover:bg-yellow-500">
           <input className="p-2 h-full w-6 flex-grow flex-shrink rounded-l-md focus:outline-none px-4" type="text" />
           <SearchIcon className="h-12 p-4"/>
         </div>
         <div className="text-white flex items-center text-xs space-x-6 mx-6 whitespace-nowrap">
         <div onClick={!session ? signIn : signOut} className="link">
         <p  className="hover:underline">
           {session ? `Hello, ${session.user.name}` : "SignIn"}
         </p>
         <p  className="font-extrabold md:text-sm">Acount & lists</p>
       </div>

           <div className=" link">
             <p>Returns</p>
             <p className="font-extrabold md:text-sm">& orders</p>
           </div>
           
           <div onClick={() => router.push('/checkout')} className=" link relative flex items-center">
             <span className="absolute top-0 right-0 md:right-10 h-4 w-4 bg-yellow-400 rounded-full text-center text-black font-bold">
                {items.lenth}
             </span>

           <ShoppingCartIcon className="h-10 "/>
           <p className="hidden md:inline font-extrabold md:text-sm mt-2">Bascket</p>
           </div>
         </div>
      </div>
         {/*bottom nav*/}
      <div className="flex items-center space-x-3 p-2 pl-6 bg-amazon_blue-light text-white text-sm">
        <p  className="link flex items-center ">
          <MenuIcon className="h-6 mr-5"/>
          all</p>
          <p className="link">featured </p>
          <p className="link">new arrival </p>
          <p className="link">catalog </p>
          <p className="link hidden lg-inline-flex">electronics </p>
      </div>
    </header>
  );
}

export default Header;

bascketslice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  items: [],
};

export const basketSlice = createSlice({
  name: "basket",
  initialState,
  reducers: {
    addToBasket: (state, action) => {
      state.items =[...state.items, action.payload]
    },
    removeFromBasket: (state, action) => {},
  },
});

export const { addToBasket, removeFromBasket } = basketSlice.actions;

// Selectors - This is how we pull information from the Global store slice
export const selectItems = (state) => state.basket.items;

export default basketSlice.reducer;

app.js

import { Provider } from 'react-redux'
import { store } from '../app/store'
import '../styles/globals.css'
import { SessionProvider } from "next-auth/react"

const MyApp = ({ Component, pageProps: { session, ...pageProps }, }) => {
  return (
    <SessionProvider session={session}>
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    </SessionProvider>
  )
}

export default MyApp

product.js

import Image from "next/image";
import {useState} from "react";
import{ StarIcon} from"@heroicons/react/solid";
import Currency from "react-currency-format";
import { useDispatch } from "react-redux";
import { addToBasket } from "../slices/basketSlice";

const MAX_RATING =5;
const MIN_RATING =1;

function Product({id, title, price, description, category,image}) {
  const dispatch = useDispatch();

  const{rating}= useState(
    Math.floor(Math.random() * (MAX_RATING - MIN_RATING +1)) + MIN_RATING
  );

  const addItemToBasket = () =>{
    const product = {
      id,
      title,
      price,
      description,
      category,
      image,
    };
    // sending product to bascket using action
    dispatch(addToBasket(product))
  };

  
  return (
    <div className="relative flex flex-col m-5 bg-white z-30 p-30">
        <p className="absolute top-2 right-2 text-xs italic text-gray-400">{category}</p>

        <Image src={image} height={200} width={200} objectFit="contain" />

        <h4 className="flex">{title}</h4>
        <div className="flex">
          {Array(rating)
          .fill()
          .map((_, i)=>(
            <StarIcon className="h-5 text-yellow-500"/>
          ))}
        </div>

        <p className="text-xs my-2 line-clamp-2">{description}</p>

        <div className="mb-5">
          <Currency quantity={price}/>
        </div>
        <button onClick={addItemToBasket} className=" mt-auto button">Add to Basket</button>
    </div>
  );
}

export default Product

package.jason

{
  "name": "with-redux-toolkit",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@heroicons/react": "^1.0.6",
    "@reduxjs/toolkit": "1.5.0",
    "@tailwindcss/line-clamp": "^0.2.0",
    "firebase": "^8.10.1",
    "firebase-admin": "^9.8.0",
    "next": "latest",
    "next-auth": "^4.3.1",
    "react": "17.0.1",
    "react-currency-format": "^1.1.0",
    "react-dom": "17.0.1",
    "react-redux": "7.2.2",
    "react-responsive-carousel": "^3.2.23"
  },
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^10.2.5",
    "postcss": "^8.2.15",
    "tailwindcss": "^2.1.2"
  }
}

files

website

the yellow circle should show the no.

this is for a website basket build please help.

please tell me if you need a GitHub repo.

i think there is a error in product.js or header.js as the no error but the no is not showing.



Solution 1:[1]

Did you switch to React 18? There seem to be problems with R18, strict mode and react-redux 7. Please update to the react-redux 8 beta in that case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 phry