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>
);