Having trouble resolving TypeScript TS2322 error with Context API + useState hook in your React App?

Currently, I am working on a React Typescript project that utilizes the Context API to pass down a useState hook.

export const AppContext = React.createContext(null);

function App() {
  const [value, setValue] = React.useState(3);

  return (
    <AppContext.Provider
      value={{
        value,
        setValue
      }}
    >
      <div>
        <h1>App</h1>
        <Child />
      </div>
    </AppContext.Provider>
  );
}

The project is functioning correctly on Code Sandbox: https://codesandbox.io/s/interesting-lamarr-fyy1b

However, upon attempting to replicate the setup in a project created with Create React App (

npx create-react-app project-name --typescript
), I encountered an error:

Type '{ value: number; setValue: Dispatch>; }' is not assignable to type 'null'. TS2322

I suspect that this issue arises because null is initially set as the value for AppContext, but it gets overridden by the value passed to the Provider.

If my assumption is correct, what would be the best way to address this problem? Could relaxing the TypeScript settings be a solution, or is there a more elegant workaround that avoids this conflict altogether? As someone new to both TypeScript and the Context API, I'm unsure if my approach is less than ideal in either aspect.

Answer №1

This particular issue does not stem from Typescript, but rather a simple adjustment in the code is required:

export const AppContext = React.createContext(null);

Should be changed to:

export const AppContext = React.createContext({});

Additionally, I suggest refactoring your Child component using AppContext.Consumer as follows:

const Child = () => {
  return (
      <AppContext.Consumer>
        {({ value, setValue }) => (
          <div>
            <h2>{value}</h2>
            <button onClick={() => setValue(value + 1)}>Click</button>
          </div>
        )}
      </AppContext.Consumer>
  );
};

Answer №2

Did you attempt to declare the State using

React.useState<number|null>

?

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

Having trouble getting material-ui container to work with custom breakpoints in TypeScript?

Currently, I am exploring material-ui and typescript within my educational project. However, I have encountered a perplexing issue for which I am seeking assistance. In this project, I utilize custom breakpoints in the material-ui theme settings. import { ...

Unable to display information stored in the Firebase database

I am struggling with a frustrating issue. My goal is to showcase the information stored in the Firebase database in a clear and organized manner, but I'm having trouble achieving this because it's being treated as an object. getData(){ firebas ...

Setting up tsconfig.json to enable support for either string literals or string templates involves adjusting the compiler options

After utilizing swagger codgen with the typescript-aurelia template to create API code, I noticed that a significant amount of string literals were being used in the resulting code. Despite encountering errors when running the transpiler tsc from the comma ...

Creating a personalized theme for Material UI 5.0 using Typescript with React

Having some trouble customizing a theme in Material UI 5.0 with typescript. theme.ts import { createTheme } from '@mui/material'; declare module '@mui/material/styles' { interface Theme { custom: { buttonWi ...

How can one pass a generic tuple as an argument and then return a generic that holds the specific types within the tuple?

With typescript 4 now released, I was hoping things would be easier but I still haven't figured out how to achieve this. My goal is to create a function that accepts a tuple containing a specific Generic and returns a Generic containing the values. i ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

Struggling with my React project, feeling stuck and unsure how to move

Hey there! I'm running into some issues with the npx create-react-app script. Every time I attempt to create a new React app, it gets stuck at this point: Creating a new React app in C:\USER\User\Document\GitHub\Projects Inst ...

Retrieve the value of a promise and transfer it to the subsequent function of an observable

For my Angular 9 application, I have created a custom interceptor called AuthorizationHeaderInterceptor: @Injectable() export class AuthorizationHeaderInterceptor implements HttpInterceptor { constructor(private authenticationService: AuthenticationSer ...

Unable to fetch data from URL in Angular using the HttpClientModule

I have a goal in my application to retrieve data from the following URL and showcase it within the app: https://jsonplaceholder.typicode.com/posts/1 The issue I'm encountering is that the data is not being displayed in my app. The console is showing ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

Are push notifications supported in Ionic3?

I've been struggling to set up push notifications in my Ionic3 app for the past couple of days, and no matter what I try, it doesn't seem to work due to the current versions I'm using. Here are my current versions: rxjs: 5.5.11 Angular: 5 ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

Touch gestures using Hammer.js including tapping and swiping downwards

Is there a way to use HammerJS in Angular Material to implement drag-down functionality that triggers an event? I want the dragdown event, as shown in the image below on the gray bar just above the Facebook button. How can I achieve this? ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

"Handling dependency injection with cyclic dependencies along with a custom implementation of HTTP and ConfigService

I am currently working on implementing a ConfigService to retrieve the appropriate configuration for each environment within the project. However, I have run into an issue with cyclic dependencies. (index):28 Error: (SystemJS) Provider parse errors: C ...

The combination of TypeScript 2.6 and material-ui 1.0.0-beta.24's withStyles with react-router withRouter is resulting in the error message: "Property 'classes' is missing in type."

Using the high order components withStyles and withRouter together has been a smooth process so far. However, after upgrading to the latest versions of these components, an error occurred. Learn more about higher-order components List of packages used: ...