Next.js does not recognize Typescript Context

I encountered an unexpected custom error while trying to implement custom error notifications in my form. The custom context I set up for this functionality does not seem to be working as intended, resulting in a thrown error for its non-existence. My development environment consists of Next.js and TypeScript.

View image description here

To address this issue, I have created a NotificationProvider component that handles the state of notification messages. It utilizes React Context API to provide a central storage for error messages. Below is the code snippet:

    "use client"
import React, { useContext } from 'react'
import { Notification } from "../components/Notification"
import { AlertColor } from '@mui/material';

type ContextProperties = {
    getError: (msg: string) => void,
}

// Rest of the code has been omitted for brevity

In addition, I've included the usage of the context within my Home component:

"use client"

import { Button, Container, Grid } from '@mui/material'
import Typography from '@mui/material/Typography'
import Image from "next/image";
import Link from 'next/link'

import { useNotification } from './context/notification.context'

// Rest of the code has been omitted for brevity

        </Grid>

          <Grid item>
            <Button variant='contained' type="button" onClick={handleClick}>Test Notification</Button>
          </Grid>
          
        </Grid>

      </Container>
    </>
  )
}

Answer №1

It appears that your setup is accurate. The only issue seems to be that you may have forgotten to wrap your app with the NotificationProvider. Since you are utilizing use client, it indicates that you are working with next.js 13. Make sure to include this in the top-level layout.tsx:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang='en'>
      <body>
        <NotificationProvider>{children}</NotificationProvider>
      </body>
    </html>
  )
}

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 to integrate authentication and authorization features into a ReactJS application with Microsoft Azure AD or Database login functionality

We have an application built on React v18 with a backend that includes a Web API and SQL Server database. Our requirement is to authenticate and authorize users using either MS Azure AD or the database. If a user attempts to log in with a username and pas ...

What is the importance of using getters for functions involving Moment.js in vueJS and typescript?

weekOfMonth() calculates the current month and week within that month. <template> <h3>{{ weekOfMonth }}</h3> </template> <script lang="ts"> export default class HomeView extends Vue { const moment = require(& ...

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Angular: Granting an external module access to a provider

One of the modules I imported provides a service with an optional dependency. Although it being optional didn't affect my application, as it just prevented any errors from occurring when not present. Here's an example: import { FooModule } from ...

Exploring the combination of MongoDB and NextJS: Easily identify corresponding data regardless of capitalization

This code aims to retrieve and display the latest data on Covid-19 related fatalities, recoveries, and critical cases worldwide. The search function is defined as: const search = (e) => { e.preventDefault() //to prevent page reload cons ...

Enhance the Material UI StepIcon by embedding real icons within the background circle

I have scoured through stack overflow but haven't come across a specific question addressing my issue. I am working on styling a Material UI Stepper component in a unique way. Most examples I've found use withStyles or makeStyles for color custom ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Creating an array with varying types for the first element and remaining elements

Trying to properly define an array structure like this: type HeadItem = { type: "Head" } type RestItem = { type: "Rest" } const myArray = [{ type: "Head" }, { type: "Rest" }, { type: "Rest" }] The number of rest elements can vary, but the first element ...

My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it en ...

What is the best way to set up deployment tracking for Next.js without using a custom server?

In the midst of developing a project using Next.js, we have opted to run it WITHOUT the custom server, instead relying on next build + next start. For our backend, whenever a new version is deployed and goes live, we notify the team through a log service. ...

Connecting a href in Material UI Drawer Component on a dynamic web page

Currently experimenting with Material UI's drawer component (https://material-ui.com/components/drawers/) for creating a navigation bar. While implementing this code into my project, I am facing some confusion regarding how to correctly link the href ...

Using TypeScript path aliases to resolve import errors

After creating a Vue.js project using Vue CLI 3 and setting up the import statement with the @ alias, I encountered an error when running npm run build. Can you explain why this happened? Error Message $ npm run build > [email protected] build / ...

Next.js version 13 now gives an error stating that the "target" property is deprecated in next.config.js. In fact, the target property is no longer present in the next.config.js configuration file

After upgrading my next.js app to Next.js 13 and deploying the new version to AWS Amplify, I encountered a build failure with the following error message: The "target" property is no longer supported in next.config.js Error: The "target" propert ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

The proper way to update MUI styles

click here to see an image I am looking to customize the background style in this code snippet: MuiAccordion: { styleOverrides: { root: { boxShadow: 'none', position: 'inherit', '& .Mui-expanded': ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

Every time I reload the page, the tab indicator on Material-UI returns to the first tab item

After integrating material-ui tabs with react router, I noticed that the tab indicator resets to the first tab upon page reload. I suspect this is due to the initial value of the tab being set to zero and resetting on page refresh. To visualize the issue, ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

Acquiring the source or domain name in Next.js

Is there a way to retrieve the origin in Next.js without using window.location.origin? The useRouter().asPath method provides the relative pathname, but how can I access the origin URL like https://www.google.com? The Next.js Router docs do not provide in ...