Guide to setting a SetState function within a component (Using NextJS and TypeScript)

I'm currently diving into TypeScript, and I've hit a roadblock when it comes to the correct assignment for my setState function that I need to pass to a component.

/index.tsx

import { Dispatch, SetStateAction, useState } from "react";
import FetchPokeAPI from "./api/FetchPokeAPI";
import Header from "./components/Header";
import ItemList from "./components/ItemList";

export interface IAllItems {
  name: string;
  url: string;
} [];

export default function Home() {

  const [allItems, setAllItems] = useState<IAllItems[]>([]);

  FetchPokeAPI(setAllItems);

  return (
    <>
      <Header />
      <ItemList items={allItems} />
    </>
  )
}
/FetchPokeAPI.tsx

import { Dispatch, SetStateAction, useEffect } from "react";
import { IAllItems } from "./../index";

interface IProps {
    setAllItems: Dispatch<SetStateAction<IAllItems[]>>;
    allItems: IAllItems[];
}

export default function FetchPokeAPI({setAllItems}:IProps) {
  const pokeapiURL:string = "https://pokeapi.co/api/v2/item/";

  useEffect(() => {
    fetch(pokeapiURL)
      .then((response) => response.json())
      .then((data) => {
        setAllItems(data.results);
      })
      .catch((error) => console.error(error));
  }, [pokeapiURL]);
}

Upon encountering this issue:

Argument of type 'Dispatch<SetStateAction<IAllItems[]>>'
  is not assignable to parameter of type 'IProps'

Thank you in advance :)

While other posts on forums have provided some guidance, I seem to be at a standstill now.

Answer №1

The reason is that the interface IProps contains 2 elements: setAllItems: Dispatch<SetStateAction<IAllItems[]>> & allItems: IAllItems[]; and you are only assigning setAllItems to it. Since you didn't include the second element, allItems, in the props, TypeScript sees two different types - type IProps which includes both elements and the current props type which only includes setAllItems.

export default function FetchPokeAPI({setAllItems}:IProps) {...

To resolve this issue, you need to include allItems in your props like this:

export default function FetchPokeAPI({setAllItems, allItems}:IProps) {...

This way, you will have a correct type assignment.

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

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

The JavaScript React Slider fails to hide the next arrow button when there are no images displayed on the screen

What I am trying to achieve is the display of a certain number of images inside a div according to the screen size. Currently, I have managed to hide the previous button when currentIndex != 0. However, I am facing difficulty in hiding the next button when ...

Caution: Unable to load bindings, resorting to pure JS instead (consider running npm run rebuild?) within AWS SAM

When I run a sam local invoke to call a typescript AWS Lambda function locally, I am encountering a warning: 2023-04-04T08:53:29.931Z undefined WARN bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) Should I conf ...

Mastering the incorporation of Context in React with Typescript

I am currently in the process of setting up a context provider for my Next.js application using TypeScript. Although I have previously set up a context provider in React using plain JavaScript, this time I am delving into learning TypeScript. In the code ...

Dynamic getter/setter in Typescript allows for the creation of functions

I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass which contains a map of containers: type Container = { get: () => Content s ...

Replicating entities in TypeScript

I am currently developing an Angular 2 application using TypeScript. In a User Management component, I have implemented a table that displays all the users in my system. When a user is clicked on within the table, a form appears with their complete set of ...

Encountering typecheck errors during the deployment of a Next.js build with a Dockerfile present

Trying to deploy a Next.js application with docker has been a bit challenging. When I run "npm run build" on my Windows machine, everything works perfectly. However, when using the Dockerfile provided by Vercel, the build fails at the "Linting and checkin ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Ordering a list of IP addresses using Angular Material table sorting

Here is an example I am baffled by the fact that Material Table sorting does not properly arrange the table. I have created a stackblitz example to demonstrate this. Expected order - Sorting lowest IP first: "10.16.0.8" "10.16.0.16" & ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Error in fetching data in Next.js API route: TypeError occurs when trying to read properties of undefined, specifically the 'headers' property

In my endeavor to establish an API route using the Next.js 13 app directory, I encountered an issue when throwing an error like this: throw createHttpError(FORBIDDEN, "You are already registered") The error message received was as follows: Err ...

Encountering an error while trying to update an Angular application to version 10

I am currently running a demo app and I am new to Angular. Below is my category list component. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; im ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

The error message "Property 'data1' is not a valid property on the object type {}"

const Page: NextPage = ({data1}:{data1:any}) => { const [open, setOpen] = React.useState(false); const [data, setData] = React.useState(data1); const handleAddClick = () => { setOpen(true); }; ..... } export async function getServerS ...

Using CamanJs in conjunction with Angular 6

Struggling to integrate camanjs with Angular 6? Wondering how to add the JavaScript library and use it within an Angular project when there are no types available on npm? Here are the steps I followed: First, install Caman using npm. Next, add it to ...

What are the best methods for visually designing a database using Entity Framework Core?

I find myself contemplating the best approach to designing my database scheme for optimal efficiency and visual appeal. Currently, I am working on an ASP.NET Core application with Angular 2, utilizing Entity Framework Core ("Microsoft.EntityFrameworkCore" ...

Utilizing the useEffect hook with outdated information

As I was learning about react hooks, I encountered a perplexing issue that I can't quite grasp. My goal is to create a list of numbers that can be incremented and should always display in descending order. However, when I input a high number initially ...

Can one inherit under specific conditions?

I have just started exploring the OOP paradigm and I am curious to know if it is possible to have conditional inheritance in TypeScript. This would help avoid repeating code. Here is what I have in mind. Any suggestions or recommendations are greatly appre ...

Build Folder not being generated in Next Js version 13.5.6

I'm running into an issue where I am unable to generate the build folder in Next.js 13.5 using npm run build. Additionally, I need to upload this dynamic Next.js project to GoDaddy cpanel. Can anyone help? Thanks! ...