Can someone provide assistance with comprehending Typescript formatting in the context of React/Next

Greetings fellow beginners! Today marks my first attempt at creating an app, and I've decided to go with Next.js as my framework due to its popularity and recommendation by React. The code snippet below sets up a simple list where you can add items using a text box and an "add" button. The tutorial I followed used javascript, but I opted for typescript. My question revolves around passing hooks from the default function into the consts below. Initially, I had:

const List = ( tasks : {id: string; task: string}[]; )

The data type of tasks is an array containing elements with id and task properties. However, I encountered an issue where it wouldn't accept this format. The solution required an additional layer, which left me puzzled:

const List = ( tasks : {tasks : {id: string; task: string}[];} )

By implementing this change, when utilizing the map function, I had to use tasks.tasks.map instead of tasks.map, which seems counterintuitive. There must be a more efficient approach. Moreover, the input for the "AddTask" const appears verbose. Is there a way to simplify this?

'use client';
import { useState } from "react";
import { v4 as uuidv4 } from 'uuid';

const initialTasks = [
  {
    id: 'a',
    task: 'Make this app',
  },
  {
    id: 'b',
    task: 'Do uni work',
  },
];

export default function Home() {
  const [tasks, setTasks] = useState(initialTasks);
  const [text, setText] = useState("");

  function addToList() {
    const newTask = {id: uuidv4(), task: text};
    setTasks([...tasks, newTask]);
    setText("");
  }

  function handleChange(event: any) {
    setText(event.target.value);
  }

  return (
    <div>
      <h1>Task Manager</h1>
      <p>To Do List:</p>
      <List tasks={tasks} />

      <AddTask 
        text={text}
        onChange={handleChange}
        onAdd={addToList}
      />
    </div>
  )
}

const List = ( tasks : {tasks : {id: string; task: string}[];} ) => (
  <ul>
    {tasks.tasks.map((task: any) => (
      <li key={task.id}>{task.task}</li>))
    }
  </ul>
);

const AddTask = ({ text, onChange, onAdd }: {text: string; onChange: (event: any) => void; onAdd: () => void}) => (
  <div>
    <input type="text" value={text} onChange={onChange} />
    <button type="button" onClick={onAdd}>Add</button>
  </div>
);

Answer №1

The components receive the first argument as the props object. To work with your component, you need to provide a tasks prop like this: props.tasks. This requires defining an object with the necessary property.

I highly recommend avoiding inline types and instead creating interfaces and types with descriptive names.

interface Task {
  id: string;
  task: string;
}

interface ListProps {
  tasks: Task[];
}

You can then utilize these interfaces appropriately in your code.

const [tasks, setTasks] = useState<Task[]>(initialTasks);

Furthermore,

const List = ({ tasks }: ListProps) => (
  <ul>
    {tasks.map(({ id, task }) => (
      <li key={id}>{task}</li>
    ))}
  </ul>
);

// Alternatively, without destructuring

const List = (props: ListProps) => (
  <ul>
    {props.tasks.map((task) => (
      <li key={task.id}>{task.task}</li>
    ))}
  </ul>
);

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

Trouble encountered with the implementation of setValue on placeholder

When I send the value for age, it is being treated as a date in the API that was built that way. However, when I use setValue to set the form value and submit the form, it also changes the placeholder text, which is not what I want. I would like the placeh ...

Throttle individual users, exclude frontend server and getServerSideProps from throttling

Currently, I am working on an application using NestJs where I've implemented the throttle module to prevent abusive requests. One aspect that has left me puzzled is whether implementing a block for abusive requests (e.g., exceeding 20 requests per m ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

What are the advantages of using useEffect without a dependency array?

As we know, utilizing useEffect without a dependency array will trigger on each render. However, this is similar to the direct inclusion of code within the component. So, what's the rationale for using it? One scenario that comes to mind is making u ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Is it possible to include a JWT token in Axios HTTP requests within a NextJS app router project?

Currently, I am utilizing Next.js 13 with app router and in search of a method to include an authorization header to the axios http request. The instance has been established as follows. The code is designed to obtain a JWT token from the cookie but unfor ...

Tips for incorporating Vanilla JS ES6 modules into TypeScript programming

Trying to incorporate the following library: spotlight, a plain JavaScript library. A dummy d.ts file was created for this project: declare module 'spotlight.js' as suggested by VSCode. Attempted various import combinations as follows: import ...

The integration of Apollo Client cache with Next.js

Hey everyone! I've been working with Next.js and the getStaticProps function to fetch data on the server side. Everything seems to be working fine, but there's one exception that's throwing me off. After using the client.readQuery({ query: ...

Managing unresolved state for server components while revalidating paths in Next.js

Recently, I've delved into the world of Next.js 14 and successfully integrated revalidatePath to trigger data refetching after a mutation in my React server components. However, I'm encountering a challenge when it comes to managing the pending s ...

How can I exclude TypeScript files generated from js in WebStorm?

Using the Enable Typescript Compiler option results in a .js file being generated for every .ts and .tsx file by the TypeScript compiler. https://i.sstatic.net/Yr0lR.jpg When performing code completion, WebStorm does not recognize that the files were aut ...

D3 version 4 with Typescript - How "this" is used in the context of d3.drag().on("end", this.dragended)

Currently, I am utilizing the D3 library for moving an element within a Venn diagram. Upon releasing the item after dragging, I aim to determine its position within the diagram. item.call(d3.drag() .on("start", this.dragstarted) .on("drag", this.d ...

Removing 'undefined' from props listed in the default props of a React TypeScript component

Summary: I am looking to create a utility function in TypeScript that can take 2 objects as input and remove any undefined values from the properties of the first object that are also present in the keys of the second object. So far, I have attempted the ...

Creating a D3 graph within a static HTML document without the need for additional wrappers or packages installation

I am currently working on a next.js (react) application and I am looking to incorporate multiple graphs that have been created as static files (HTML, CSS, JS). Can someone guide me on how to achieve this? One of the example graphs I am referring to can be ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: https://i.sstatic.net/icZOb.png The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This ...

Error TS2339: The member 'sort' is not found in the type 'BehaviorSubject<AbstractControl[]>'

Looking to create a dynamic table using Angular material where I can dynamically add or remove data. As a newcomer to Angular, I found the following StackBlitz helpful in setting up the table: https://stackblitz.com/edit/angular-material-editable-table-fa ...

Create a debounce click directive for buttons in a TypeScript file

I'm facing an issue with implementing debounce click on a dynamically added button using TypeScript. I need help with the correct syntax to make it work. private _initActionsFooter(): void { this.actionsFooterService.add([ { ...

The module "@clerk/nextjs/server" does not contain a member with the name "clerkMiddleware" available for export

Currently, I am working on Nextjs 14 with typescript and implementing authentication and authorization using Clerk. Following the instructions in the Clerk documentation, I included the code snippet below in my middleware.ts file: import { authMiddleware } ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Discovering if a page can be scrolled in Angular

Hey there, I recently started working with Angular and created an app using the angular material stepper. The issue I'm facing is that some of the steps have longer content, causing the page to become scrollable. I am now trying to find a way to deter ...

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...