I will try to keep it simple.
I have a list of todos which are displayed in a todo page.
I have a “number of todos” which are displayed on a home page.
I am trying to update in real time the “number of todos” when a user adds a new todos to the list.
My issue is that the state will not update until I refresh the “number of todos” home page. I want it to update in real time without the user having to refresh the page manually.
I am fairly new to react and not really sure what’s going on.
This is the relevant code.
const [todos, setTodos] = useState([]);
const [stats, setStats] = useState("");
useEffect(() => {
setStats(todos.length);
}, [todos]);
const addTodo = async (todo) => {
const id = uuidv4();
const datetime = format(new Date(), "MMMM dd, yyyy HH:mm");
const newTodo = { id, todo, datetime };
try {
const response = await api.post("/todos", newTodo);
const updatedTodos = [...todos, response.data];
setTodos(updatedTodos);
setStats(updatedTodos.length);
setNewTodo(""); // reset the todo so it reset the input field as well
} catch (err) {}
};
<Routes>
<Route path="/" element={<Home stats={stats} />} /> ....
import React from "react";
const Home = ({ stats }) => {
return (
<div>
<h2 className="HomeTitle">HomePage</h2>
<main className="Home">
<p> Welcome to this website </p>
<p>Number of Posts: {stats}</p>
</main>
</div>
);
};
export default Home;