In my React todo list application hosted here, I have a few basic states:
const [todos, setTodos] = useState([]);
const [status, setStatus] = useState("all");
const [sortBy, setSortBy] = useState("created-asc");
const [starredToggle, setStarredToggle] = useState(false);
Where:
- todos is an array of objects that hold data relating to a test
- status is a state selected through radio buttons
- sortBy is a state selected through a dropdown menu
- starredToggle is a boolean tied to a checkbox input
I have the following useEffect calls:
useEffect(() => {
getLocalTodos();
saveLocalTodos();
}, [])
useEffect(() => {
filteredTodosHandler();
saveLocalTodos();
}, [status])
useEffect(() => {
filteredTodosHandler();
saveLocalTodos();
}, [todos])
useEffect(() => {
sortByHandler();
}, [sortBy])
useEffect(() => {
filteredTodosHandler();
}, [starredToggle])
In addition to localStorage functions:
const saveLocalTodos = () => {
localStorage.setItem("todos", JSON.stringify(todos));
};
const getLocalTodos = () => {
if (localStorage.getItem("todos") === null) {
localStorage.setItem("todos", JSON.stringify([]));
} else {
let localTodo = JSON.parse(
localStorage.getItem("todos", JSON.stringify(todos))
);
setTodos(localTodo);
}
};
Where:
-
gets the list of todos from local storage and then saves them (the save seems to be redundant, I removed from my active code)
-
When status is changed, filter then save the todos
-
When the todos array is changed, filter them and then save
-
When the sort by drop-down state is changed, sort them
-
When the starred toggle checkbox is clicked, filter by sorted
The fourth one sorts the array, but ends up wiping local storage on refresh. I can’t figure out what is going on to cause this. The choice to use local storage was introduced through the tutorial I based this on, but supported by the idea that it is meant only to be a single-user application without authentication. I don’t know if local storage is the best call or if there’s something better. This is driving me crazy and I just want to see it through to the end!