Skip to content

Instantly share code, notes, and snippets.

@natafaye
Created July 25, 2022 03:35
Show Gist options
  • Save natafaye/3a3be98ea56245bd6b310dbd5295fa6a to your computer and use it in GitHub Desktop.
Save natafaye/3a3be98ea56245bd6b310dbd5295fa6a to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from 'react'
// Note: This function could be combined with the refreshTasks function
const fetchAllTasks = async () => {
// Get the response
const response = await fetch("/api/tasks");
// Parse the data from the response
const data = await response.json();
// Handle how Mirage.js packages up the response
return data.tasks;
}
// Note: This function could be combined with the onDeleteClick function
const deleteTask = async (id) => {
// Make a delete request to the backend for the task with a particular id
await fetch("/api/tasks/" + id, { method: "DELETE" })
}
export default function App() {
const [taskList, setTaskList] = useState( [] )
// Note: this function could be inside the useEffect side effect function
const refreshTasks = async () => {
// Get the tasks from the backend
const freshTasks = await fetchAllTasks();
// Set the state to the fresh tasks and trigger a re-render
setTaskList(freshTasks);
}
// kick off fetching the data after the first render
useEffect(() => {
refreshTasks();
}, []) // Only run once (twice in development with Strict Mode) after the first render
const onDeleteClick = async (id) => {
// tell the backend to delete something
await deleteTask(id);
// Options for keeping the frontend and backend in sync
// OPTION 1: Ask the backend for the data again
refreshTasks();
// OPTION 2: Make the same change on the frontend
// setTaskList(currTaskList => currTaskList.filter(task => task.id !== id))
}
return (
<ul>
{ taskList.map(task => (
<li key={task.id}>
{ task.name }{" "}
<button onClick={() => onDeleteClick(task.id)}>Delete</button>
</li>
))}
</ul>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment