The parameter type is not compatible with the argument type of 'SetStateAction'

I am new to next.js and typescript and I encountered a typescript error in vscode. Even though it does not impact the state variable, I am curious to understand why the error occurs and how to resolve it

Error message: "Argument of type 'Movie | undefined' is not assignable to parameter of type 'SetStateAction<Movie | null>'. Type 'undefined' is not assignable to type 'SetStateAction<Movie | null>'"

Tsx snippet:

import { useEffect, useState } from "react";
import { Movie } from "typings";

interface Props {
  netflixOriginals: Movie[];
}

export default function Banner({ netflixOriginals }: Props) {
  const [movie, setMovie] = useState<Movie | null>(null);

  useEffect(() => {
    setMovie(
      netflixOriginals[Math.floor(Math.random() * netflixOriginals.length)]
    );
  }, [netflixOriginals]);

  console.log(movie);

This line triggers the error when setting state:

netflixOriginals[Math.floor(Math.random() * netflixOriginals.length)]

typings file:

export interface Movie {
    title: string
    backdrop_path: string
    media_type?: string
    release_date?: string
    first_air_date: string
    genre_ids: number[]
    id: number
    name: string
    origin_country: string[]
    original_language: string
    original_name: string
    overview: string
    popularity: number
    poster_path: string
    vote_average: number
    vote_count: number
  }

When console logging the state, it retrieves a random item from the list. I am interested in learning how to correctly handle this according to typescript rules.

I understand that if the array were empty, it would result in an 'undefined' value, but I can ensure that it always contains elements from the parent component. How can I specify to typescript that it will always return a 'Movie' type

Answer №1

When you select a movie item from a list called netflixOriginals using this syntax:

netflixOriginals[some_random_number]
, the resulting type is Movie|undefined.

If you initially defined your state as Movie|null, you can consider changing null to undefined.

const [movie, setMovie] = useState<Movie | null>(null);

To make this adjustment, it would look like:

const [movie, setMovie] = useState<Movie | undefined>(undefined);

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 is the best way to execute a function on the output of *ngFor directive in Angular 2?

Imagine having a list of all the users within your system: allUsers = { a: {name:'Adam',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39585d5854794d5c4a4d5a56175a56... f: {name:'fred' ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

Is it necessary to utilize the useState() function during the signup process, even when a defaultValue is not present?

Exploring the world of React I have embarked on a project to build a website using Next.js, and I am currently working on a signup page. Throughout most of the page, I have been utilizing useState to manage values and interact with APIs. However, I find ...

Leveraging context.query in Next.js 13

It seems like the context.query I was relying on in Next.js 12 isn't functioning in version 13. What alternative can I use instead of context.query? Should I switch to Context API or useSearchParams? As a beginner developer, I'm feeling quite los ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

Issue with image not loading on Next [email protected] while utilizing Image component from next/image along with tailwindcss class

I am trying to make my image responsive on mobile view. I have used tailwindcss classes to set the Image className, and it works fine when I only use reactjs or a regular img tag. I am attempting to make this image responsive. I have tried setting the layo ...

The concept of a generic type serving as a characteristic of an incoming argument

What is the best way to assign a type property of an argument to a generic in TypeScript? Here's the code snippet: const foo = <T = someObject.bar>(someObject: {[string]: any}): T => { return someObject.bar } How can we set the type of ...

What are common pitfalls to avoid when modifying state with createSlice in Redux-Toolkit?

I am currently working with the createSlice function, specifically with the reducer setCustomEquipment that updates the state. My question is whether the = method is an acceptable way to update the state when using createSlice, or if I should always use ...

What is the process for retrieving the GitHub username in the GitHub OAuth Next.js sign-in callback in order to store it in a database?

1. Detail the issue I am facing a challenge while developing a Full Stack Website using Next.js and Typescript. Specifically, I am having difficulty persisting the Github Username in the database when a user signs in via Github OAuth. Should I consider st ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...

The use of window.Image() is ineffective when working with TypeScript and React

In my React project, I am utilizing the KonvaJS library. You can find more information about it here. To display an image using JavaScript/React, I have implemented the following code: componentDidMount() { const image = new window.Image(); ima ...

"Exploring the New Feature of Angular 17: Named Router Outlets Implemented

One issue I am facing with my application is the rendering of different pages based on whether a user is logged in or not. The generic pages like the landing or logout page should be displayed within the primary router-outlet when the user is not logged in ...

Stripe vs. Next 14 - PaymentElement Mystery: Where did it go?

I have double-checked my setup, and so far everything seems to be error-free. My server-side code is within the page component, which can be found here: https://github.com/erasebegin/heard-good-things-shop/blob/main/src/app/%5Bslug%5D/checkout/page.tsx Th ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Unable to Identify Actual Type from Global Declaration within TypeScript Project References

For the purpose of demonstrating my issue, I have set up a demo repository. This repository comprises two projects: electron and src, both utilizing TypeScript project references. In the file src/global.d.ts, I have defined the type API_TYPE by importing ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

A guide to removing a cookie in a Next.js 14 middleware following verification from an external API

I'm currently working on an application using Next.js 14 and I've encountered an issue related to cookie management within my middleware. The main objective is to make a call to an external API to validate the user's token. In case the valid ...