'Why Separate function's returned value mutates props values in React?
I am following a course, sorting logic comes from "sortQuotes" function and storing its returned data to "sortedQuotes" constant, so how is it possible that even though I am not passing that modified data to JSX and still rendering original props.quotes - code works and pressing sorting button changes list to ascending/descending correctly?
const sortQuotes = (quotes, ascending) => {
return quotes.sort((quoteA, quoteB) => {
if (ascending) {
return quoteA.id > quoteB.id ? 1 : -1;
} else {
return quoteA.id < quoteB.id ? 1 : -1;
}
});
};
// props.quotes -----> [{id:'q1'},{id:'q2'},{id:'q3'}]
const QuoteList = props => {
const navigate = useNavigate();
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const isSortingAscending = queryParams.get('sort') === 'asc';
console.log(props.quotes);
// Even before "sortQuotes" function call on the first render, props.quotes are still changed in order
const sortedQuotes = sortQuotes(props.quotes, isSortingAscending);
const changeSortingHander = () => {
navigate(`/quotes?sort=${!isSortingAscending ? 'asc' : 'des'}`);
};
return (
<>
<div className={classes.sorting}>
<button onClick={changeSortingHander}>
Sort {isSortingAscending ? 'Descending' : 'Ascending'}
</button>
</div>
<ul className={classes.list}>
{props.quotes.map(quote => (
<QuoteItem
key={quote.id}
id={quote.id}
author={quote.author}
text={quote.text}
/>
))}
</ul>
</>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
