skip to Main Content

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


  1. You should filter the original list not the already filtered list (;

    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(
        ContentList.filter((cont) => cont.category == selectedCategory)
        //^HERE^
        );
      };
    

    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.

    Login or Signup to reply.
  2. 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 DRYDo 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

    const { useState } = require('react');
    
    export default function App() {
      const [selection, setSelection] = useState('all');
      return (
        <>
          <ul>
            {list
              .filter((item) =>
                selection == 'all' ? true : item.category === selection
              )
              .map((item) => (
                <li key={item.name}>{item.name + ',' + item.category}</li>
              ))}
          </ul>
          <button onClick={() => setSelection('red')}>Red</button>
          <button onClick={() => setSelection('green')}>Green</button>
          <button onClick={() => setSelection('yellow')}>Yellow</button>
          <button onClick={() => setSelection('blue')}>Blue</button>
          <button onClick={() => setSelection('all')}>All</button>
        </>
      );
    }
    
    const list = [
      {
        name: 'a',
        category: 'red',
      },
      {
        name: 'b',
        category: 'green',
      },
      {
        name: 'c',
        category: 'green',
      },
      {
        name: 'd',
        category: 'blue',
      },
      {
        name: 'e',
        category: 'yellow',
      },
      {
        name: 'f',
        category: 'red',
      },
      {
        name: 'g',
        category: 'green',
      },
    ];
    

    npm list

    [email protected]
    ├── [email protected]
    ├── [email protected]
    └── [email protected]
    

    Test run results:

    1. All – on load of the form

    list of items - all

    1. On selecting green

    list of items - green only

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search