skip to Main Content

Tasks doesn’t update (not unless I refresh the page) after submitting/creating a new task. Seems like the useEffect is not running during handleSubmitForm.

import React, { useEffect, useState } from "react";


const Tasks = () => {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    getTasks();
  }, []);

  const getTasks = async () => {
    const response = await ('/tasks/');
    const data = await response.json()
    setTasks(data);
  };

  const [task, setTask] = useState("");

  const handleSubmitForm = (e) => {
    fetch("/tasks/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ title: task, completed: false }),
    })
  };

  return (
    <ul>
      <div>
        <input
          onInput={(e) => {
            setTask(e.target.value);
          }}
          value={task}
        />
        <button onClick={handleSubmitForm}>Add</button>
      </div>
      {tasks.map((task) => {
        return <li key={task.id}>{task.title}</li>;
      })}
    </ul>
  );
};

export default Tasks;

I’m fairly new with react and it’s 2 days now I still can’t figure it out.

2

Answers


  1. After successfully submitting a new task, you should add it to your tasks array. After that React will automatically re-render your tasks for you (since your tasks state was updated).

    const handleSubmitForm = (e) => {
        fetch("/tasks/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ title: task, completed: false }),
        }).then(() => {
          setTasks([...tasks, { title: task, completed: false }]);
        })
    
      };
    
    Login or Signup to reply.
  2. All you have to do is call getTasks() in the .then of your fetch function

    const handleSubmitForm = (e) => {
        fetch("/tasks/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ title: task, completed: false }),
        }).then(() => {
           getTasks();
        })
    
      };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search