When I open the app, useEffect successfully transfers the data to my app via fetch function and the app re-renders so that the todos are displayed.
If I create a new todo via handleCreateTodo, send it to the server via a post request and then call the fetch function, the database is updated but the app does not Re-Render. I have to refresh the browser manually so that the new todo is displayed.
import { FunctionComponent, ReactElement, ChangeEvent, MouseEvent, useState, useEffect } from "react";
import { v4 } from "uuid";
import axios from "axios";
const endpoint = 'http://localhost:8000';
let currentTodos: Todos [];
export const TodoTable: FunctionComponent = (): ReactElement => {
const [todos, setTodos] = useState<Array<Todos>>([]);
const [enterTodo, setEnterTodo] = useState<string>('');
//Get Todos from DB
const fetchTodos = async() => {
const { data, status } = await axios.get(endpoint + '/todos');
if(status == 200){
setTodos(data);
}
}
useEffect(() => {
fetchTodos();
}, []);
//Enter Todo handler
const handleEnterTodo = (event: ChangeEvent<HTMLInputElement>): void => {
setEnterTodo(event.currentTarget.value);
};
//Create Todo handler
const handleCreateTodo = async () => {
//create new Todo
const newTodo = {
//id: todos.length+1,
id: v4(),
describtion: enterTodo,
done: false
};
const { status } = await axios.post(endpoint + '/todos', newTodo);
if(status == 200){
fetchTodos();
}
setEnterTodo('');
};
return(
<>
<div className="todoTable">
<InputBar
enterTodo={ enterTodo }
handleEnterTodo={ handleEnterTodo }
handleCreateTodo={ handleCreateTodo }
handleClearTodos= { handleClearTodos }
/>
<TodosDisplay
todos={ todos }
handleDeleteTodo={ handleDeleteTodo }
handleStatus={ handleStatus }
/>
</div>
</>
);
}