The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message:

Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; initializeOnMount: true; }' is not assignable to type 'IntrinsicAttributes & MoralisProviderProps'.
  Types of property 'appId' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.ts(2322)

The type signature for MoralisProvider is as follows:

const MoralisProvider: ({ children, appId: _appId, serverUrl: _serverUrl, jsKey, dangerouslyUseOfMasterKey, plugins, environment, getMoralis, options: { onAccountChanged }, 
initializeOnMount, }: MoralisProviderProps) => JSX.Element

The code snippet for mounting the component:

import MoralisProvider
import type { AppProps } from 'next/app';
import { MoralisProvider } from 'react-moralis';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <MoralisProvider
      appId={process.env.NEXT_PUBLIC_MORALIS_APP_ID}
      serverUrl={process.env.NEXT_PUBLIC_MORALIS_SERVER_ID}
      initializeOnMount
    >
        <Component {...pageProps} />
    </MoralisProvider>)
}

export default MyApp;

Answer №1

Upon realizing that it was only anticipating a string, I resolved the TypeScript warning by utilizing template literals:

      appId={`${process.env.NEXT_PUBLIC_MORALIS_APP_ID}`}
      serverUrl={`${process.env.NEXT_PUBLIC_MORALIS_SERVER_URL}`}

Answer №2

The issue highlighted by Typescript is not related to initializeOnMount, but rather with the appId. When using process.env, you will receive an object that may or may not have the required values. It is recommended to extract these values before mounting and verify their existence. One simple approach is:

const getEnvValue = (key: string): string => {
  if (!process.env[key]) {
    throw Error("Please handle this scenario")
  }

  return process.env[key]
}

The challenge lies in deciding how to handle the error if it occurs, which will vary based on the specifics of your project.

Answer №3

all process.env values are string | undefined

implementing nullish coalescing to address the issue

import MoralisProvider
import type { AppProps } from 'next/app';
import { MoralisProvider } from 'react-moralis';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <MoralisProvider
      appId={process.env.NEXT_PUBLIC_MORALIS_APP_ID ?? "AppId Undefined Fallback"}
      serverUrl={process.env.NEXT_PUBLIC_MORALIS_SERVER_ID ?? "ServerUrl Undefined Fallback"}
      initializeOnMount
    >
        <Component {...pageProps} />
    </MoralisProvider>)
}

export default MyApp;

tip

inject app with MoralisProviderProps. Create a types/next.d.ts file and define it as follows:

import type { NextComponentType, NextPageContext } from "next";
import type { AppInitialProps } from "next/app";
import type { Router } from "next/router";
import type { MoralisProviderProps } from 'react-moralis';

declare module "next/app" {
  type AppProps<P = Record<string, unknown>> = {
    Component: NextComponentType<NextPageContext, any, P>;
    router: Router;
    __N_SSG?: boolean | undefined;
    __N_SSP?: boolean | undefined;
    __N_RSC?: boolean | undefined;
    pageProps: P & {
       moralisProps: MoralisProviderProps;
    };
  };
}

if you only want to pass in appId and serverUrl as props, then define a custom type for _app

import type { NextComponentType, NextPageContext } from "next";
import type { AppInitialProps } from "next/app";
import type { Router } from "next/router";
import { MoralisProvider } from 'react-moralis';

export declare const customAppProps: {
  appId: string | undefined;
  serverUrl: string | undefined;
} = {
  appId: process.env.NEXT_PUBLIC_MORALIS_APP_ID,
  serverUrl: process.env.NEXT_PUBLIC_MORALIS_SERVER_ID
};

declare module "next/app" {
  type AppProps<P = Record<string, unknown>> = {
    Component: NextComponentType<NextPageContext, any, P>;
    router: Router;
    __N_SSG?: boolean | undefined;
    __N_SSP?: boolean | undefined;
    __N_RSC?: boolean | undefined;
    pageProps: P & {
      customProps: typeof customAppProps;
    };
  };
}

Then modify _app like this

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <MoralisProvider
      appId={pageProps.customProps.appId}
      serverUrl={pageProps.customProps.serverUrl}
      initializeOnMount
    >
        <Component {...pageProps} />
    </MoralisProvider>)
}

export default MyApp;

Important -- this technique is particularly handy for global context providers such as apollo client's normalized cache object or authentication tokens like jwt for session management

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

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

I'm looking to conceal the error overlay on Nextjs

I am in the process of creating a platform for trading Solana NFTs with Next.js. My goal is to remove the error overlay, similar to what is shown in this image: Any suggestions on how to achieve this? ...

An unexpected TypeScript error was encountered in the directory/node_modules/@antv/g6-core/lib/types/index.d.ts file at line 24, column 37. The expected type was

Upon attempting to launch the project post-cloning the repository from GitHub and installing dependencies using yarn install, I encountered an error. Updating react-scripts to the latest version and typescript to 4.1.2 did not resolve the issue. Node v: 1 ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Is there a resource or extension available for identifying design flaws in Typescript code?

Currently, I am in the midst of an Angular project and am eager to identify any design flaws in my Typescript code. Are there any tools or extensions available that can help me pinpoint these design issues within my project? Any assistance would be greatl ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Gain access to TypeScript headers by typing the request (req) object

Is there a way to access headers in a method that is typed with Express.Request? Here's an example code snippet: private _onTokenReceived(req: Express.Request, res: Express.Response): void { const header: string = req.headers.authorizatio ...

Having trouble downloading Next.Js as I continuously encounter the error message "Module Not Found."

Struggling to download Next.Js and encountering the error message "Cannot find Module" view image here Any assistance would be greatly appreciated as this is time sensitive. I attempted to reinstall Node.js but unfortunately, it did not resolve the issue ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Ways to compel string type or disregard type?

When using the following code snippet: <Image src={user?.profilePictureUrl} alt={user?.name} /> An error is encountered: Type 'string | null | undefined' is not assignable to type 'string | StaticImport'. Type 'undefined ...

Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the app/App_Resources/Android/app.gradle file: // Uncomment to add recyclerview-v7 dependency dependencies ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

RxJS: the art of triggering and handling errors

This is more of a syntax question rather than a bug I'm facing. The process is straightforward: Send an HTTP request that returns a boolean value If the boolean is true, proceed If the boolean is false, log a warning and stop the flow. To handle ...

Is it feasible to use a component in a recursively manner?

Following a two-hour search for a solution, I decided to reach out to experts as I suspected the answer might be simpler than expected. The project in question is an Angular7 one. In my goals component, I aim to include a "goal" with a button labeled "+". ...

Create an interface that adheres to the defined mapped type

Working on a typescript project, I have defined the mapped type GlanceOsComparatorV2 interface DonutData { label: string; value: number; } interface ProjectMetric { value: number; } enum ZoneMetricId { ClickRate = 'clickRate', } enum Pa ...

Transferring data between browser tabs in Next.js and automatically populating a formik form

I have a form on my page with a single input field for a name. When this form is submitted, I want to open a new tab in the browser that displays a form with more inputs such as name, address, and age. How can I pre-fill the name in the new tab? I was thi ...

Guide on how to display the next/image on a public IP domain

Hello, I am facing an issue with getting the src URL image using next/image. I have already set it up in next.config.js but I am still encountering errors. Here is my code: index.js <Image src={'http://110.100.190.222:9790/images/'+item.artic ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...