javascriptreactjsreact-hooks

react setState() not triggering re-render


I have component which receives data from other file and setting into state:

const [sortedPlans, setSortedPlans] = useState(
    data.Plans.sort((a, b) => b.IndustryGrade - a.IndustryGrade)
  );//data is from external file

After setting the state, sorting the data and rendering the initial screen, I have function that sorts the sortedPlans whenever it is called:

const sort = (event) => {
    console.log(event);
    const newArr = sortedPlans.sort((a, b) => {
      return b[event] - a[event];
    });
    console.log(newArr);
    return setSortedPlans(newArr);
  };

The problem is that this is never triggering a re-render of the component. I want when I set the new state to be able to see it inside the jsx. Why when I console.log(newArr) the results are correctly sorted but this setting of the state not triggering re-render? Here is the sandbox:

https://codesandbox.io/s/charming-shape-r9ps3p?file=/src/App.js


Solution

  • Here you go: Codesandbox demo.

    You should first make a shallow copy of the array you want to modify. Then set that array as the new state. Then it re-renders the component and you are able to filter like you want.

      const sort = (event) => {
        console.log(event);
        //shallow copying the state. 
        const newArr = [...sortedPlans];
    
        //modifying the copy
        newArr.sort((a, b) => {
          return b[event] - a[event];
        });
        console.log(newArr); //results here are correctly sorted as per event
        
        //setting the state to the copy triggers the re-render.
        return setSortedPlans(newArr);
      };