I have an array of objects that is filled from a json file.
import ContentList from "../lists/contentList.json";
Contentlist
In my App, I want to be able to select a category and show only the objects of that category.
Green selected
My approach was this:
I have a copy of my ContentList, the RenderList, which is the list that gets rendered.
Each time a filter-button is pressed in the app, the function handleSelectCategory gets triggered, which should update the RenderList.
import ContentList from "../lists/contentList.json";
import { useState } from "react";
function Body() {
const [selectedCategory, setSelectedCategory] = useState("all");
const [RenderList, setRenderList] = useState(
ContentList.map((e) => ({ ...e }))
);
const handleSelectCategory = (category: string) => {
setSelectedCategory(category);
resetRenderList();
updateRenderList(category);
};
const resetRenderList = () => {
setRenderList(ContentList.map((e) => ({ ...e })));
};
const updateRenderList = (selectedCategory: string) => {
setRenderList(
RenderList.filter((cont) => cont.category == selectedCategory)
);
};
Right now the filter works the first time I press a button, but when I then press a different button, the list is empty. So the RenderList seems to not be resetted to the original ContentList. I just started learning React and couldn’t find an answer to that specific problem.
2
Answers
You should filter the original list not the already filtered list (;
if you wondering why the
resetRenderList
doesn’t do the same thing then remember Calling the set function does not change state in the running code, which implies that you can’t call setState sequentially and expect it to work. It will update the state on the next render so you shouldn’t call it multiple times.It may help if you review your code based on what is a state and what should not be a state ?
As you know, the React system reacts to the changes in state, and thus it makes the UI interactive.
Let us discuss the interactions in your app.
The first interaction is when the user clicks on the button and makes a selection. And the corresponding reaction expected in the UI is that the list should filter and display accordingly. Therefore which is the absolute minimal representation of state to keep in the app? It is the only one state with respect to the selection. Once this piece of state is made available in the app, a lot of information can be computed based on it. For example, a filtered list can be computed based on the state changes in selection. This approach is in line with the principle DRY – Do not repeat yourself. This has been discussed based on the documentation here.
Now coming to the code, selectedCategory is the minimal required state. The RenderList can always be computed. This will reduce the code in the app as well. Please see below a sample code done based on these lines. Please see if it is useful. You can also see the test results enclosed below.
App.js
npm list
Test run results: