Mastering the Application of useSelector with TypeScript

I am using the useSelector code snippet below:

const  user  = useSelector<RootStateOrAny, typeof typeRootReducer>((state) => state.user)

This is how it looks in the rootReducer:

const rootReducer = combineReducers({
    user: userReducer
})


export default rootReducer
export type typeRootReducer = ReturnType<typeof rootReducer>

Initial State:

const initState = {
    user: null
}

Whenever I try to access console.log(user.user.name), I get an error message saying

cannot read property name of null

Answer №1

It appears that your user is null, as you mentioned in your code. This leads to the error when you try to access null.name. Your selector usage seems fine, but there may be an issue with the data in your state not aligning with your code.

To simplify and avoid dealing with type errors, consider creating a pre-typed hook like useAppSelector. With this, you can easily retrieve state values like

const user = useAppSelector(state => state.user)
while ensuring correct typing.

For detailed guidance on setting up TypeScript with Redux Toolkit, check out the TypeScript Quick Start tutorial.

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

Tips for excluding test files in next.js when building

I am currently developing a next.js application with tests integrated within the page directory structure. In order to achieve this, I have made necessary configurations in the next.config.js file. const { i18n } = require('./next-i18next.config' ...

Is it possible to create a single directive that can handle both Structural and Attribute behaviors?

Trying to develop an Angular Directive that will handle various functionalities based on config input values Dynamically add elements to the DOM based on input values (similar to ngIf) Apply styling to rendered elements Add attribute properties such as d ...

Remove any extra spaces at the end of a copied number when using Angular

Is there a way to automatically remove spaces at the end of a 10-digit number when it is copied from another source (like email or Word documents) and pasted into the search bar? Currently, this function only works when we press enter. I would like for bl ...

Error in Firestore Update: Integrating arrayUnion in Firestore Update Operation

Currently, I'm encountering a problem when attempting to update a Firestore document by adding an element to an array field using Firestore's 'arrayUnion' method. My Angular application is integrated with Firestore through AngularFire, ...

Is there a way to utilize redux to trigger the opening of my modal when a button is clicked?

I'm facing a challenge with opening my modal using redux when clicking <CheckoutButton/>. Despite my efforts, the modal keeps appearing every time I reload the browser. I've reviewed my code but can't pinpoint the issue. What am I doin ...

Comparing Node.JS using Typescript versus Javascript to Ruby On Rails

My question can be simplified as follows: 1. Does Ruby perform as well as Node with MongoDB? 2. Should I use Typescript or JavaScript with Node? I come from a .NET background (ASP.NET MVC) and am now venturing into creating an Angular project with a Mongo ...

Is there a way to include two objects in an Angular2 post request?

This piece of code is giving me trouble: On the client side (using Angular 2) saveConfig(configType: ConfigTypes, gasConfigModel: GasConfigModel): any { console.info("sending post request"); let headers = new Headers({ 'Content-Type& ...

Enhancing external access

I am currently working on enhancing the types of convict. The current definitions export convict using the following: namespace convict { ... } interface convict { ... } declare var convict: convict; export = convict; To augment the interface, I have mad ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...

Angular Bootstrap Modal not Displaying

<img id="1" data-toggle="modal" data-target="#myModal" data-dismiss="modal" src='assets/barrel.jpg' alt='Text dollar code part one.' /> <div id="myModal" class="modal fade" *ngIf="isModalShowing"> <div class=" modal-lg ...

Expanding on the http class to utilize custom properties within Angular2 typescript

I have developed a CustomHttp class that extends Http similar to the example provided here: To integrate this CustomHttp class, I included providers in the bootstrap function as shown below: bootstrap([ HTTP_PROVIDERS, { provide:Http, use ...

Generate written output using a collection of C# class titles on a typewriter

I need help finding a setup or template file for creating TypeScript files based on a group of C# classes with Typewriter. Here's an example of what I'm looking for: $Classes(['myclass1','myclass2','myclass3'])[ ...

Guide to adding the current date into a URL with Angular

I'm a little confused at the moment and could use some guidance. My goal is to dynamically insert the current date into an API URL using Angular. Here is the progress I have made so far: Below is my Typescript code: import { HttpClient} from '@a ...

Move your cursor over a specific element to trigger an effect on another element that is not directly next to or related to it

In my current project, which is built with Angular, I am looking for a way to achieve a specific effect without using jQuery. Specifically, I would like the text inside a div element with the class title to have underline styling when hovering over an im ...

Challenges faced with implementing Tailwind CSS within the pages directory of NextJS websites

Issue with Tailwind Styles I've encountered a problem where the Tailwind styles are not being applied to components in the /pages directory of my NextJS project. Oddly enough, the same component works fine when used outside the pages directory. When ...

Maintain user authentication in Firebase as long as the localStorage object remains active

I am currently working on an app using Ionic, Angular2, and Firebase. My approach involves saving the auth.currentUser information in the localStorage when a user logs in or registers. However, I recently discovered that having the user variable set in th ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

Replace i18next property type in React for language setting

We have decided to implement multilanguage support in our app and encountered an issue with function execution. const someFunction = (lang: string, url: string) => any If we mistakenly execute the function like this: someFunction('/some/url', ...

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...