How to generate an unique id for each Component of initial value of useState()

I want to create 30 empty Taskcard components at the beginning of the state my problem is that each Taskcard has the same id how can I fix that?

import React from 'react'
import { useEffect, useState } from 'react'
import { getTasks } from '../api/task.api'
import { TaskCard } from './TaskCard'


export function TaskLists() {
    const [tasks, setTasks] = useState(Array(30).fill({id: 1, title: 'title', description: 'description'}))

   useEffect(() => {
     async function loadTasks() {
        const res = await getTasks();
        console.log(res.data)
        setTasks(res.data);
     }
     loadTasks();
   },[]);

   const removeTask = (id) => {
        setTasks(tasks.filter(task => task.id !== id));
   }

  return (
    <div>
        {tasks.map((task) => (
            <TaskCard key={task.id} task={task} onDelete={removeTask} />
        ))}
    </div>
  )
}

  • fill()ing with an object fills it with references to the same object. see the docs: Array.prototype.fill()

    – 




  • Does this answer your question? How do I use array.fill for creating an array of objects?

    – 

  • But more curiously you are setting an initial array, and then immediately overwriting it with the fetched data in the useEffect.

    – 




  • 1

    It wont get another 30, as you are setting tasks state in useEffect,and on load first useEffect will be called every time.

    – 

  • 1

    I dont know what UX you want, but the best thing here you can do is to show loader before you get API response, and then directly show correct data instead of dummy data.

    – 

Try, this hosuld work

const [tasks, setTasks] = useState([...Array(10).keys()].map(x => { return {id: x+1, title: 'title', description: 'description'}}))

Leave a Comment