Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 22 additions & 18 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,46 @@
import React, { useEffect, useState, useRef } from "react";
import "./App.css";
import "./server";
import React, { useEffect, useState, useRef } from 'react';
import './App.css';
import './server';

function App() {
let [isLoading, setIsLoading] = useState(true);
let [isSaving, setIsSaving] = useState(false);
let [todos, setTodos] = useState([]);
let [newTodo, setNewTodo] = useState("");
let [newTodo, setNewTodo] = useState('');
let inputEl = useRef(null);

useEffect(() => {
fetch("/api/todos")
fetch('/api/todos')
.then(res => res.json())
.then(json => {
setIsLoading(false);
setTodos(json);
});
}, []);

useEffect(() => {
if (isSaving) {
fetch('/api/todos', {
method: 'POST',
body: JSON.stringify({ todo: { text: newTodo } }),
})
.then(res => res.json())
.then(data => {
setIsSaving(false);
setTodos(state => [...state, data]);
setNewTodo('');
inputEl.current.focus();
});
}
}, [isSaving]); // eslint-disable-line react-hooks/exhaustive-deps

function handleChange(event) {
setNewTodo(event.target.value);
}

function handleSubmit(e) {
e.preventDefault();
setIsSaving(true);

fetch("/api/todos", {
method: "POST",
body: JSON.stringify({ todo: { text: newTodo } })
})
.then(res => res.json())
.then(newTodo => {
setIsSaving(false);
setTodos([...todos, newTodo]);
setNewTodo("");
inputEl.current.focus();
});
}

return (
Expand All @@ -50,7 +54,7 @@ function App() {
value={newTodo}
onChange={handleChange}
className={`w-full shadow rounded px-3 py-2 focus:outline-none focus:shadow-outline ${isSaving &&
"opacity-75"}`}
'opacity-75'}`}
autoFocus
placeholder="What needs to be done?"
ref={inputEl}
Expand Down
Loading