Search code examples
reactjsreduxnext.js

TypeError: Cannot destructure property 'count' of '(0 , react_redux__WEBPACK_IMPORTED_MODULE_3__.useSelector)(...)' as it is undefined


Following this tutorial: https://www.youtube.com/watch?v=iBUJVy8phqw

I would like to set up REdux in my Next.js app. But I got stuck. Do not know why. Everything is the same as in the tutorial.

counter.js:

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

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0,
  },
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    },
    incrementByAmount: (state, action) => {
      state.count += action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

store.tsx:

import { configureStore } from "@reduxjs/toolkit";
import { counterReducer } from "./counter";

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
});

first part in onboarding2.tsx:

import Head from "next/head";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";

export const fallBackLang = "hu";

interface Onboarding2Props {
  lang: string;
  translations: Translation;
}

export default function Onboarding2(props: Onboarding2Props) {
  const { lang, translations } = props;
  const { count } = useSelector((state) => state.counter);

enter image description here


Solution

  • You have attempted to import 'counterReducer' which is not present in counter.js

    'counterReducer' is ought to be the counterSlice.reducer which is exported as default from counter.js

    You could simply replace

    import { counterReducer } from "./counter";
    

    with

    import counterReducer from "./counter";
    

    in your store.js file