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

Recommendations for organizing code with respect to models in Angular using TypeScript

Within my C# backend, I structure my entities and entity lists using classes. Any needed functions or methods are simply added to the corresponding class. On the contrary, in Angular/TypeScript examples, models are typically defined as interfaces. This ra ...

Grab the current URL using useRouter in a Next.js app

I am using userouter to obtain the URL of the current page and then utilizing the clipboard to copy it. However, I am encountering an issue where the copied content shows as object object instead of the expected URL. Can someone please help me identify w ...

Establishing a connection pathway for communication among components in Angular

I am faced with a situation where I have two components, CompA and CompA5, that are 3 or 4 levels apart. I need to establish a means of communication between these components. For instance, I want component CompA to send an event to CompA5, receive some d ...

Get notified with ng2-smart-table updates when editing

I am trying to control the edit feature of my ng2-smart-table, but the code I have isn't working. Am I missing something? HTML <ng2-smart-table [settings]="settings" [source]="source" (edit)="onEdit($event)"></ng2-smart-table> Component ...

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

Tips for including HTML content in an agm-marker using Angular 2

In my Angular 2 application using agm map for vehicle tracking, I am looking for a way to customize the map marker. Specifically, I want to display the vehicle status by changing the color of the marker (green for running, red for stopped, yellow for idle) ...

Working with form data in Next.js

I am a newcomer to NEXT JS and I am facing an issue with sending form data from the client to the NEXTJS API. After searching for a solution for a few days, I found some explanations but couldn't quite grasp them. I would greatly appreciate it if some ...

Is it possible for Typescript interface A to extend B while lacking certain properties from B?

My confusion lies in understanding how TypeScript interfaces function effectively. Here's what I currently have: import type { Socket, Handshake } from 'socket.io'; import type { Session } from './session'; export interface Sessio ...

Module 'ngx-bootstrap' not found in project

My application is encountering an issue with ngx-bootstrap where the module can no longer be detected unless the path is specified. For instance: import { BsModalService, BsModalRef } from 'ngx-bootstrap'; results in "Cannot find module ' ...

The value of form.formGroup is not equivalent to the output of console.log(form)

Having an issue here. When I send a Form to a component, If I use console.log(form), it displays the object correctly. However, when I check the form in the console, the form.formGroup.value looks fine (e.g. {MOBILE0: 'xxx', PHONE0: 'xxx&ap ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

Checking for a nonce in OIDC custom provider authentication for NextAuth

Currently, I am utilizing an IDP that necessitates a nonce for security purposes. In my NextAuth configuration, I have included the nonce in the authorization step with the following setup: import NextAuth, { NextAuthOptions } from 'next-auth' c ...

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...

Is there a way to compare data before and after revalidation using useSWR?

With the use of Next.js and through the implementation of useSWR, data is fetched from an endpoint every 30 seconds using an automatic revalidation interval (https://swr.vercel.app/docs/revalidation#revalidate-on-interval). Within the retrieved data, there ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

The lack of synchronization between the updated state in one function and its counterpart is causing discrepancies, resulting in the incorrect information being sent to the API

Whenever I press the following button: <Button onClick={(e) => { addToCard(item); handleprisma(); }} > add to cart </Button> This function is meant to add the item to my shopping cart: const addToCard = (item) => { co ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Should the page.js in a Next.js App router be a server component?

Is it standard practice in Next.js 13 and above (App router) for the page.js of all routes/folders to be a server component? I know that it can be a client component with use client, but is this advisable or are there potential issues during the build proc ...

Could we potentially pause the map and insert a different element into the center instead?

I am currently working on creating a navbar in Nextjs, and I have a specific requirement to include a different element in the middle of the navigation links. {navLinks.map((link, index) => ( <li key={index}> ...

Setting up Electron to utilize TypeScript's baseUrl can be achieved by following a few simple steps

In TypeScript, there is a compiler option known as baseUrl that allows you to use non-relative paths, like: import Command from "util/Command" as opposed to: import Command from "../../../util/Command" While this works fine during compilation, TypeScri ...