I am learning React following this video, and while adding a new object to the state array containing all the tasks in this to-do list app changes are not getting immediately rendered but rather after some other state change when I write a different version of what I understand to be doing the same stuff from the video but if I exactly write video’s version then its getting rendered immediately.
Inside App.js :
let initialTasks = [
{
id: 1,
title: "Doctor's Appointment",
date: "10th Feb, 2023",
reminder: true,
},
{
id: 2,
title: "College Fest",
date: "18th Feb, 2023",
reminder: false,
},
{
id: 3,
title: "Mid-Semester exams",
date: "21th Feb, 2023",
reminder: true,
},
];
let [tasks, setTasks] = useState(initialTasks);
let [showForm, setShowForm] = useState(false);
My version of addTask function:
const addTask = (task) => {
let tempTasks = tasks;
tempTasks.push({ id: 10, ...task });
setTasks(tempTasks);
};
Working version from the video:
const addTask = (task) => {
const newTask = { id: 10, ...task };
setTasks([...tasks, newTask]);
};
In my version the task state is getting updated but is not rendering immediately but renders after showForm state changes. Any help is appreciated.
Link to GitHub repo if needed: https://github.com/ayush0402/react-tasker
2
Answers
Your version with comments:
Working version with comments (use this version):
Combining them:
I hope this helps!
Edit:
As pilchard mentioned, the combination I’ve exemplified above is incorrect because it mutates the state (
tempTasks
is a reference totasks
) and even though in most scenarios it might work fine, it can sometimes cause unexpected behaviour. Therefore, stick to the working version.Let’s Make It Simple
Paste Above Code in Your File and Try It Will Work.