Tips for setting up the preloadedState in the redux global store

My current React Redux app store setup using TypeScript looks like this:

import { configureStore } from '@reduxjs/toolkit';
import rootReducer from '../reducer/combineReducer';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';

const logger = createLogger(); 
const initialState = {
    
};

const store = configureStore({
    reducer: rootReducer,
    middleware: [logger, thunk],
    devTools: process.env.NODE_ENV !== 'production',
    preloadedState: initialState
});

export default store;

However, I want to add some initial global data structure in the preloadedState, so I updated the initialState code like this:

const initialState = {
    user: {}
};

But now I'm seeing an error in Visual Studio Code:

Type '{ user: {}; }' is not assignable to type '{ readonly [$CombinedState]?: undefined; user?: { user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined; }'.
  Types of property 'user' are incompatible.
    Type '{}' is not assignable to type '{ user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined'.ts(2322)
configureStore.d.ts(45, 5): The expected type comes from property 'preloadedState' which is declared here on type 'ConfigureStoreOptions<CombinedState<{ user: { user: any; loginUser: {}; } | { loginUser: any; user: {}; }; }>, any, Middleware<{}, any, Dispatch<AnyAction>>[], [...]>'
(property) ConfigureStoreOptions<CombinedState<{ user: { user: any; loginUser: {}; } | { loginUser: any; user: {}; }; }>, any, Middleware<{}, any, Dispatch<AnyAction>>[], [...]>.preloadedState?: {
    readonly [$CombinedState]?: undefined;
    user?: {
        user: any;
        loginUser: {};
    } | {
        loginUser: any;
        user: {};
    } | undefined;
} | undefined

What should I do to successfully add some initial global field definitions?

Answer №1

The solution can be found in the error message:

 Type '{}' is not compatible with type '{ user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined'

In TypeScript, it expects the value of user to be an object containing user and loginUser fields, but you are passing an empty object instead. Include these fields in the object to resolve the issue.

The definition of ConfigureStoreOptions further elaborates on this:

/**
 * The initial state, similar to Redux's createStore.
 * You can specify it to preload the state
 * from the server in universal apps, or to restore a previously serialized
 * user session. If you utilize `combineReducers()` to create the root reducer
 * function (either directly or indirectly by providing an object as `reducer`),
 * this must be an object with the same structure as the reducer map keys.
 */
preloadedState?: DeepPartial<S extends any ? S : S>

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

Interactive MUI React Tab Components

Currently, I am working with MUI tabs and have added an X button to them. However, I am facing difficulties in making the tabs closeable. I would greatly appreciate any help or guidance on how to achieve this feature. Despite trying different methods, I ha ...

React Link updates the URL without re-rendering the view

I'm encountering an issue with the <Link to=""> element in React. When I click on it, the URL changes but the view remains the same. However, upon refreshing the page, the correct component is displayed indicating that the router is functioning ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...

Setting up Emotion js in a React TypeScript project using Vite 4

Currently, I am in the process of transitioning from Webpack to Vite for my React Typescript application. I have been attempting to integrate Emotion js into the project. "@vitejs/plugin-react": "^4.0.1", "vite": "^4.3.9 ...

A guide on customizing the height of MUI Datepicker input box in a React application

<DesktopDatePicker label="Expiration Date" inputFormat="MM/dd/yyyy" value={self.didexpirationdate} onChange={(e)=>{ setSelf({...self,didexpirationdate:e}) }} renderInput={(params) => <TextField {. ...

Shattering the barrier

When using the bubble chart, I encountered an issue with adding line breaks in text. No matter what I tried, such as using \n or , it consistently showed me an error. import React from 'react'; import { BubbleChart,key,data } from 're ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

Difference between client-side and server-side output arises when dealing with a logged-in user (hydration error)

Encountering React's hydration error, as explained in the documentation, is attributed to "using browser-only APIs like window or localStorage in your rendering logic." This issue arises when checking for user login status throughout the application ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

When executing code in React JS, I encountered no errors, but the output did not match my expectations

I am facing a challenge with running the Hello World program in React JS using webpack. Attached below is the project structure for reference: https://i.stack.imgur.com/tQXeK.png Upon executing the npm run dev command in the CLI, the browser launches bu ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

Implement Material UI customization for the MUI X datepicker

I've been struggling to customize the date picker in MUI X by trying to remove the padding from the input field, but no matter what I do it doesn't seem to work. Am I missing something or does MUI X not support styling for this? import { styled } ...

Gatsby Functions: Exceeding payload size limit error - request entity too large

I am currently working on a Gatsby app and utilizing Gatsby Functions to obscure form submissions to an external API. The issue I am facing is that when a user attaches a file in the form, it could potentially surpass the default size limit of 100KB. While ...

Incorporating External JavaScript Files into React Components

Upon further reflection and experimentation, I've come to the conclusion that a more appropriate question would be "How can I convert JS expressions/logic into React components and props?" After examining numerous React examples, it appears that my JS ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

Encountering a gyp error while trying to run npm install on Ubuntu

I've recently started working with React and I'm facing an issue while trying to clone a git repository. When I attempted to run npm install to set up the necessary dependencies, I encountered an error on my initial attempt. The error message wa ...