Dispaying Error Message¶
We are done with all functionality, but it would be nice if we improve UX by displaying the error message if some error occures.
We will update our TodoList
container and display message if exists in store below ListHeader
. We will also add some Tailwind classes so it looks a bit nicer.
import { useDispatch, useSelector } from "react-redux";
import ListHeader from "../components/ListHeader";
import List from "../components/List";
import { addItem, getTodos, markItemAsDone, removeItem } from "../store/actions/todo";
import { useEffect, useState } from "react";
import { RootState } from "../store/reducers";
function TodoList() {
const dispatch = useDispatch();
const [title, setTitle] = useState<string>("");
const todo: any = useSelector((state: RootState) => state.todo);
const addItemToList = () => {
if (!title) return;
dispatch(addItem(title));
setTitle('');
};
const removeItemFromList = (item_id: string) => {
dispatch(removeItem(item_id));
};
const toggleItemDone = (item_id: string) => {
dispatch(markItemAsDone(item_id));
};
useEffect(() => {
dispatch(getTodos());
}, []);
return (
<div className="flex justify-center items-center h-screen">
<div className="shadow-lg rounded-lg w-[500px]">
<ListHeader
addItemToList={addItemToList}
title={title}
setTitle={setTitle}
/>
{todo.error !== '' &&
<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-5 mr-8 ml-8" role="alert">
<span className="block sm:inline">{todo.error}</span>
</div>
}
<List
list={todo.todo_list}
removeItemFromList={removeItemFromList}
toggleItemDone={toggleItemDone}
/>
</div>
</div>
);
}
export default TodoList;
Since we implemented our application in a right way, it will be hard to produce an error an make it appear. But we can simply close our backend Node.js application so our client application gets a network error.
After we do that and reload our client application, it should display an error box with "Something went wrong." message since it is unable to fetch the data.