What are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown.

To tackle this issue, I implemented a type guard function.

import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query";

export default function isFetchBaseQueryError(
    error: unknown
): error is FetchBaseQueryError {
    return typeof error === "object" && error != null && "status" in error;
}
if (!isLoginLoading && error) {
    if (isFetchBaseQueryError(error)) {
        notification.error({
            message: "Login Failed",
            description: error.data.message, // this line is causing error
        });
    }
}

Answer №1

Here is an interesting code snippet for you to check out: https://codesandbox.io/s/icy-fire-hsjoqx?file=/src/App.tsx

import get from 'lodash/get'

function validateFetchBaseQueryError(
  error: unknown
): error is FetchBaseQueryError & { data: { message: string } } {
  return (
    typeof error === "object" &&
    error != null &&
    "status" in error &&
    "data" in error &&
    !!get(error, "data.message") // ensure data.message exists
  );
}

const error = { data: { message: "message" }, status: "403" };
if (validateFetchBaseQueryError(error)) {
  console.log(error.data.message);
}

const error1 = { status: "403" };
if (validateFetchBaseQueryError(error1)) {
  console.log(error.data.message);
} else {
  console.log("data.message not defined");
}

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

Make the text stand out by highlighting it within a div using a striking blue

Currently, I am working with Angular2 and have incorporated a div element to display multiple lines of text. Positioned below the text is a button that, when clicked, should select the entirety of the text within the div (similar to selecting text manually ...

Learning how to utilize localstorage in Next-Auth once a user has been authorized

import { NextAuthOptions } from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import axios from "axios"; import NextAuth from "next-auth/next"; ...

When sharing content or using other tools, the dynamic metadata in Next.js 13.4 is not appearing as expected

When I visit the dynamic routes pages of my published site and try to share it on social media or check its SEO using tools like "https://metatags.io/", the metadata is not displaying. However, when I inspect the elements in Google Developer Tools, I can s ...

SplitChunks in Webpack 4 helps to cache modules so they do not need to be reprocessed

Currently, I am working on a TypeScript project that utilizes node packages and webpack for compiling and bundling. The folder structure of my project is as follows: Scripts App Various Modules Utility Various Utility components a ...

I am experiencing issues with the NextJs Form as it is not allowing me to enter any text into

Currently, I am in the process of creating a basic form to send messages to my email using EmailJS. The configuration settings for EmailJS seem correct as I tested them on the website and received a 200 response. This is the code snippet I have implemente ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Issue with Angular 12.1: Unable to retrieve value using "$event.target.value"

I am just starting to dive into the world of Angular and have been using YouTube tutorials as my guide. However, I have encountered an error in one of the examples provided. Below is the code snippet that is causing me trouble. HTML <input type=" ...

Sharing information with a service in Ionic and Angular

I need to send data to my service and incorporate it into a URL string. The code snippet below shows how I am obtaining the data in my constructor when the user navigates to the page: constructor(public alertController: AlertController, pri ...

Guide to creating animations with javascript/react js

My attempt at altering the opacity of an element every 100 milliseconds following a click event has not been successful. The function change is triggered by a click, yet the code does not work as intended. Here's what I have so far: function change (i ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

Unable to connect to localhost nodejs server from Windows browser when using WSL2

My computer runs on Windows 10 and has the Linux (Ubuntu-20.04) subsystem using WSL2. I've successfully initiated a frontend project (vue project) and running npm run serve works as expected with the application running on localhost:8080. However, whe ...

Error message: Unable to locate module when utilizing my alternative library packaged with Rollup

Currently, I am utilizing rollup to package a UI library for use across various primary applications. However, the bundled ESM file contains imports that are incompatible with webpack in the main applications: import { ArrowDropDownCircleOutlined } from &a ...

Guide on updating a value in a Firestore document using Firebase

I am working on updating a specific portion of a document in my Firebase collections structure, specifically the phonebook(map) section. https://i.sstatic.net/UmHot.png When attempting to modify the document, I encountered an error saying Invalid documen ...

verifying the date in a specific moment

Is there a way to validate the date accurately? to determine whether she cleared it or not. I've exhausted all my options. Despite reading through the documentation, I am unable to get it right. Here is what I attempted: if ('2023-03-03 ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

Discovering the generic parameter types with union in TypescriptUncover the

I've been struggling with the code snippets below for a while. Can someone explain why e4 is defined as string and not String? type PropConstructor4<T = any> = { new(...args: any[]): (T & object) } | { (): T } type e4 = StringConstructor ext ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...