An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools and the application appears to be functioning properly, I'm experiencing

Unexpected key "foo" found in the previous state received by the reducer. 
Expected to find one of the known reducer keys instead: [...]. Unexpected keys will be ignored.

which is puzzling to me. I've tried searching for solutions, but none of the resources I came across were specific to a custom store enhancer scenario.

Below is the minimal code that triggers this error. I'm setting up my store like this:

export const store = configureStore({
    reducer: mainReducer,
    enhancers: [testEnhancer],
});

Where mainReducer simply combines all slices with combineReducers({ "my slices" }), and all the slices are generated using createSlice from RTK.

The testEnhancer function is structured as follows:

type StateExt = { foo: string }
export const testEnhancer: StoreEnhancer<{}, StateExt> = (next: StoreEnhancerStoreCreator): StoreEnhancerStoreCreator<{}, StateExt> => {
    
    return <S, A extends Action = AnyAction>(reducer: Reducer<S, A>, preloadedState?: PreloadedState<S>): Store<S & StateExt, A> => {
        
        const wrappedReducer: Reducer<S & StateExt, A> = (state, action) => {
            return { ...reducer(state, action), foo: 'bar' };
        };
        
        return next(wrappedReducer, { ...preloadedState, foo: '' });
    };
};

Answer №1

The behavior described here is unique to the combineReducers function. It requires a fixed 1:1 relationship between top-level state keys and corresponding slice reducers.

To address this, you will have to create a custom reducer that can manage this requirement, or opt not to utilize combineReducers altogether. There are alternative implementations available that offer similar functionality without the associated warnings.

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

Can a function be annotated in order to inform the TypeScript compiler that it has verified the type of a class property?

How can I annotate `readText` in the code snippet below to assure the compiler that `this.text` is of type `string` and not `string | undefined`? type MyResponse = { text: () => Promise<string>; }; class ResponseVerfier { response: MyRespons ...

Tips for correctly sending the response code from a Node.js API

I have a straightforward node-based API that is responsible for parsing JSON data, saving it into a Postgres database, and sending the correct response code (e.g., HTTP 201). Here is an excerpt of my code: router.route('/customer') .post(fu ...

Is it possible to export multiple named exports in a single set without changing how variables are called?

In my constants file I have: export const CONSTANT1 = 'CONSTANT1'; export const CONSTANT2 = 'CONSTANT2'; export const CONSTANT3 = 'CONSTANT3'; export const CONSTANT4 = 'CONSTANT4'; export const CONSTANT5 = 'CONS ...

The function mustAsync onSuccess is not present in this type (typescript)

I currently have 2 mutations that are functioning well. However, I encountered an issue when attempting to implement onSuccess and invalidateQueries. The error message displayed is as follows: Property 'mutateAsync' does not exist on type '{ ...

Tips for utilizing canReuse and routerOnReuse in Angular 2

I've reviewed the information provided in this link, but I'm still unsure about how to effectively utilize it. My requirement is straightforward—I need to update a parameter in the URL without constantly sending API requests, which are current ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Dialog component from HeadlessUI doesn't support the Transition feature

Currently working with Next.JS version 14.1.3 I recently integrated the <Dialog> component from HeadlessUI and configured TailwindCSS. However, I encountered an issue where the Modal window doesn't have any transition effects even though I foll ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

Is it advisable to opt for window.webkitRequestAnimationFrame over setInterval?

Trying to figure out the best method for moving game characters in my JavaScript game - should I go with window.webkitRequestAnimationFrame or stick with setInterval? Any advice is appreciated! ...

acquiring data via fetch (transferring information from javascript to php file)

I'm completely new to using fetch and not familiar with Ajax. Currently, I am attempting to transfer data from a JavaScript file (node.js server) to a PHP file (Apache server). The data being sent consists of 2 JSON values labeled as "a" and "b". T ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb Public Class WebService Implements IWebService Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings Return "Greetings, dear " & name End Function End Class FILE IWebServ ...

Implementing 'Load more...' in Rails for infinite scrolling instead of traditional pagination

I currently have a collection of items and have been utilizing the will_paginate gem. However, I am interested in implementing a "load more..." feature at the end of the list. Is there a straightforward way to achieve this with will_paginate, or should I e ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Ensuring User Information Persistence in React Upon Successful Login

I am developing a small application using React with PHP as the back-end. Within my database, I have two types of users - admin and student. Upon user login, I store their information in session storage like this ( user: { username:'abcxyz123', r ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

What is the best way to implement callbacks with $http in Typescript?

When making my $http call, I am looking for the most adaptable way to handle all the parameters returned in the .success and .error functions. Here is an example of what my $http call looks like: this.$http({ url: "/api/x", method: "GET" }) .success((? ...

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

Combining Multiple Optional Async AJAX Calls

In my Angular 1.5.8 app, I have different views that require various combinations of the same 3 ajax requests. Some views need data from all three endpoints, while others only need data from one or two. To efficiently manage the retrieval of this data, I ...