Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run useEffect in React after POST request?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading