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

Struggling with converting blob file to an image within a NextJS application using data from a MySQL database

Currently, I am in the process of working on a project where I need to retrieve an image stored as a blob file in my database. However, for some reason, the image is not displaying properly. Here is the code snippet from the first file, products.jsx: impo ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

What impact does setting 'pathmatch: full' in Angular have on the application?

When the 'pathmatch' is set to 'full' and I try to delete it, the app no longer loads or runs properly. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { H ...

Error: Incorrect format detected. Expected a numerical value, but received: "t". This issue occurred when attempting to provide a slug URL to the GraphQL query function within a Next.js application

Encountering an error while attempting to retrieve content based on the URL. Here is the query function being used: const getSlugQuery = (slug) => { const SLUG_QUERY = gql` query ($slug: String!) { postCollection(where:{slug:${slug}}) { ...

A beginner's guide to implementing syntax code highlighting with next-mdx-remote

My goal is to showcase my code syntax utilizing next-mdx-remote on my Nextjs website. I'm fetching my markdown content from graphcms and displaying it in the following way: import { serialize } from "next-mdx-remote/serialize" import { MDXRemote } fr ...

Exploring the World of Dynamic Routing in Next.js version 13

I'm using Next 13 for dynamic routing with a simple setup. In my file structure, I have a component containing an array of objects and I want to display the dynamic data on the [slug] page.jsx accordingly, such as showing the data for 'lion' ...

Ensure all fields in an interface are nullable when using TypeScript

Is it possible to create type constraints in TypeScript that ensure all fields in an interface have a type of null? For example, if I want to write a validation function that replaces all false values with null, how can I achieve this? interface y { ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Mastering responsive layout design in Nextjs using Tailwind CSS

I am attempting to design a card layout where the image is on the left and the content of the card is on the right using flex in NEXTJS and Tailwind CSS. My goal is to ensure that the image remains responsive. <div className="block"> < ...

Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to al ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

The size of your request header section is too large and has exceeded the allowable limit

We have implemented AWS Amplify for our NextJS web application and are encountering errors only when attempting to load the deployed version on Amplify. Interestingly, there are no issues when running the app locally. https://i.stack.imgur.com/TacWk.png ...

What is the method for retrieving a result field based on its column name when working with oracledb in a nodejs environment

I'm currently using oracledb version 5.5.0 and facing an issue with accessing query results in OracleDB. While performing a SELECT statement, I can only access the result by the index of the column. Is there a way to retrieve it by the column name? H ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

Error in Next.js: The 'extendable-media-recorder-wav-encoder' npm package is throwing a 'Blob is not defined' error

When using the 'connect' function from this package, importing it normally works fine. However, when trying to import it dynamically as shown here, a type error occurs. The error message reads: Argument of type '() => Promise<(port: g ...

There seems to be a syntax error in the regular expression used in Angular TypeScript

I've encountered an error and I'm struggling to identify the syntax issue. core.mjs:6495 ERROR SyntaxError: Invalid regular expression: /https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2020-01-30,toDateTime ...

Having trouble capturing emitted events from a child component in Angular 2+?

I have a question as a beginner. I'm trying to send a message from the child component to the parent component but for some reason, it's not working. app.component.html <app-cart-component> [items]="rootItems" (outputItems)=&quo ...

Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password. I attempted to retrieve the values using JavaScript's getAttr ...

I am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

How can I implement a button in Angular Ag Grid to delete a row in a cell render

I have included a button within a cell that I want to function as a row deleter. Upon clicking, it should remove the respective row of data and update the grid accordingly. Check out the recreation here:https://stackblitz.com/edit/row-delete-angular-btn-c ...