2

I have this error:

enter image description here

How to fix this. What did I do wrong? I'm using Next.js 14.

/store/index.js

import { configureStore } from '@reduxjs/toolkit'
import cartReducer from './cartSlice';

export const makeStore = () => {
    return configureStore({
        reducer: {
            cart: cartReducer
        }
    })
}

/app/StoreProvider.js

"use client"
import { useRef } from 'react'
import { Provider } from 'react-redux'
import { makeStore } from '../store'
// import { cartSlice } from '../store/cartSlice'

export function StoreProvider({ children }) {
    const storeRef = useRef()
    if (!storeRef.current) {
        // Create the store instance the first time this renders
        storeRef.current = makeStore()
    }

    return <Provider store={storeRef}>{children}</Provider>
}

/app/layout.js

import { Inter } from "next/font/google";
import "./globals.css";
import { StoreProvider } from "./StoreProvider.js";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
    title: "Shopping App",
    description: "Test Data Pro",
};

export default function RootLayout({ children }) {
    return (
        <StoreProvider>
            <html lang="en">
                <body className={inter.className}>{children}</body>
            </html>
        </StoreProvider>
    );
}

I want to use Redux to save my cart item, but I write follow document https://redux.js.org/usage/nextjs but it doesn't work as expected.

1 Answer 1

2

The code is passing the React ref as the store value instead of the ref's value, which is the instantiated Redux store you want to provide. Pass store={storeRef.current} instead of store={storeRef}.

export function StoreProvider({ children }) {
  const storeRef = useRef();

  if (!storeRef.current) {
    // Create the store instance the first time this renders
    storeRef.current = makeStore();
  }

  return <Provider store={storeRef.current}>{children}</Provider>;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.