Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  164] [ 5]  / answers: 1 / hits: 7474  / 2 Years ago, wed, april 6, 2022, 12:00:00

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



More From » reactjs

 Answers
3

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);
};

[#216] Monday, March 28, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;