It appears that you are currently utilizing legacy implementation in your code. To ensure optimal performance, we recommend updating your code by incorporating createWrapper() and wrapper.useWrappedStore()

I am encountering an issue while using redux toolkit with Next.js. I am receiving the following legacy warning-

/!\ You are using a legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore().

I am unsure of where the problem lies and how I need to update my code.

Here is the code snippet:

This is store.ts-

import { Action, configureStore, ThunkAction } from "@reduxjs/toolkit";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import { combinedReducer } from "./Reducer";

const reducer: typeof combinedReducer = (state, action) => {
    if (action.type === HYDRATE) {
        const nextState = {
            ...state,
            ...action.payload,
        };
        return nextState;
    } else {
        return combinedReducer(state, action);
    }
};

export const makeStore = () => configureStore({ reducer });

type Store = ReturnType<typeof makeStore>;

export type AppDispatch = Store['dispatch'];
export type RootState = ReturnType<Store['getState']>;
export type AppThunk<ReturnType = void> = ThunkAction<
    ReturnType,
    RootState,
    unknown,
    Action<string>
>;

export const wrapper = createWrapper(makeStore);

Here is reducer.ts-

import { combineReducers } from '@reduxjs/toolkit';

export const combinedReducer = combineReducers({
    //All reducers
});

Here is Hook.ts-

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './Store';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

And finally, here is app.tsx-

function MyApp(props: MyAppProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <NextProgress
          delay={2000}
          options={{ showSpinner: false }}
          color="#eb5525"
        />
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  );
}
export default wrapper.withRedux(MyApp);

*** I do not receive any warnings with this code. However, after updating to the latest packages in my project, I am encountering the error.

Please guide me on where exactly I need to make changes in my code based on the warning?

Answer №1

The alert is triggered on this particular line of code. Anytime someone utilizes the wrapper.withRedux method (the outdated method), this warning will surface.

To resolve this issue, we need to utilize useWrappedStore for generating a store, and employ react-redux's Provider for passing down the store to the child components:

import { FC } from "react";
import { Provider } from "react-redux";
import type { AppProps } from "next/app";
import { wrapper } from "../app/store";

const MyApp: FC<AppProps> = ({ Component, ...rest }) => {
  const { store, props } = wrapper.useWrappedStore(rest);
  const { emotionCache = clientSideEmotionCache, pageProps } = props;
  return (
    <Provider store={store}>
      <CacheProvider value={emotionCache}>
        ...
        <Component {...pageProps} />
        ...
      </CacheProvider>
    </Provider>
  );
};

export default MyApp;

Answer №2

It appears that their documentation is not completely up-to-date on this issue. Based on this code snippet, here is how your MyApp should be structured:

function MyApp(props: MyAppProps) {
  const { Component, ...rest } = props
  const { emotionCache = clientSideEmotionCache, pageProps } = wrapper.useWrappedStore(rest);
  return (
   <Provider store={store}>
    <CacheProvider value={emotionCache}>
      // ...
    </CacheProvider>
   </Provider>
  );
}
export default MyApp;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Export all except those from the module in ESM

Suppose I have two imports containing numerous named exports, too many to list individually, and I need to reexport them while excluding a few due to naming conflicts. For example, consider the following two files: foo.js: export const a = 1; export cons ...

Tips for transforming Http into HttpClient in Angular 5 (or higher than 4.3)

I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient. So far, I have taken the following steps: In App.module.ts: imported { HttpClientModule } from "@angular/common/http"; Added HttpClientModul ...

Issues with importing auth0-js in a typescript, react, nextjs environment cause failures

I've been working on integrating auth0-js into my client-side project using react, typescript, and nextjs. Despite my efforts, I keep encountering the following error: Module not found: Error: Can't resolve 'auth0-js' in '/usr/src/ ...

The notion of await goes beyond simply waiting for a promise to be fulfilled

Hey there everyone! I've been struggling with a problem for some time now, and I just can't seem to figure it out by simply searching online. That's why I'm turning to all of you for help. Situation: I'm working on a small applic ...

Unable to locate the name 'JSON' in the typescript file

I have been working on an angular application where I have implemented JSON conversion functionalities such as JSON.stringify and JSON.parse. However, I encountered an error stating 'Cannot find name 'JSON''. Furthermore, there is anoth ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

Obtaining an instance of the CKEditor Editor in TypeScript with CKEditor 4: what's the best way?

Can someone explain how to utilize the CKEDITOR 4 plugin in TypeScript for an Angular 9 application? I am looking to set the configuration through TypeScript (specifically for autogrow) and also implement an INSERT HTML function. I have already imported ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

Having trouble opening a modal view from an action sheet button

Currently, I am in the process of working on a school project and facing an issue where I am trying to open a modal view from an action-sheet button. However, I encounter the following error message: TypeError: Cannot read property 'addMedicationModal ...

Changing the color of an Angular <div> element with scripting

I am currently working on an Angular 6 project and I need to change the colors of a div tag from a script after a click function. However, I also need to change it back to transparent. When I click on the "Inheritance" option, the background color of the ...

Learning how to implement the "as" syntax in TypeScript

Currently tackling an angular project that is functioning flawlessly, yet encountering a linting test failure. Unfortunately, the information provided in this post did not offer much assistance. The error message I'm facing reads as follows: ERROR: C ...

Tips for ensuring the correct function type in TypeScript

TypeScript Version 3.5.1 Playground I've encountered an issue with TypeScript where the compiler fails to flag missing arguments in function declarations. Here's a basic illustration of the problem. interface IArgs { foo: number; } type MyF ...

Issue with recognizing global methods in Vue and Typescript – help needed

I have a Vue mixin that looks like this: const languageMixin = Vue.extend({ methods: { $getLanguages: function(): object { return { en: 'english' } } } } Vue.mixin(languageMixin) ...

Struggling with getting autocomplete and auto import to work properly while working on an Angular project

After installing the latest version of VSCode on my Windows system, I proceeded to add language support for TypeScript and configure my editor settings by adjusting the font size, disabling the minimap, enabling autosave on focus change, and more. Addition ...

Enhancing Redux Form: Steps to incorporate a function post-validation and pre-submit operations

I am working on a redux form with validation functionality. Once the validation is successful and there are no errors, the form is automatically submitted to the controller using the handleSubmit() method. class SomeComponent extends Component { constru ...

Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line: const firstRef = ref<HTMLElement>(null) <template> <input id="first" ref="firstRef"> <button type="button&q ...

Mocking Dependencies in TypeScript with Jest

Here is the content of my index.ts file: import {IS3Client, S3Client} from './client/S3Client'; const s3: IS3Client = new S3Client(); export async function someFunc(event: any, context: any, callback: any) { const x: string = await s3.getFil ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

I am having trouble with the TypeScript compiler options not being detected in Visual Studio 2015

After creating an ASP.NET 5 Empty Website project in Visual Studio 2015, I set up a tsconfig.json file with the following settings: { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false ...

Using TypeScript with generic parameters allows for flexibility while still being able to verify if a specific property is present

I am in the process of gradually converting a large SvelteKit application to TypeScript, focusing on refining the API layer. Currently, I am grappling with a function that has two generics: // Function that either performs a POST or a PUT export function s ...