I get data from useQuery
.
And I want to sort them by data field directFeedNumber
.
const { data: allFeedData, loading: allFeedLoading } =
useQuery(SEE_ALL_FEED_ORDER);
const FeedSort = allFeedData.seeAllFeedOrder.sort(function (a, b) {
return a - b;
});
So I use sort
function to do this, but when I console.log FeedSort
, it says Attempted to assign to readonly property.
So can't I use sort
function with data got from useQuery
?
Then how can I sort them? Please help me!!
CodePudding user response:
Array.sort
alters the original array, unlike other methods such as Array.map
which produce a new array.
In order to prevent this, we can make a shallow copy of the original array.
Example:
const { data: allFeedData, loading: allFeedLoading } = useQuery(SEE_ALL_FEED_ORDER);
const FeedSort = [...allFeedData.seeAllFeedOrder].sort(function (a, b) {
return a - b;
});
What we do here is create a new array and populate it with the values of the original array using the spread syntax.
Then we sort the newly created array, which we can alter.
Note: there are also other ways of making shallow copies, or deep copies for that matter, of arrays and objects.
Here are some other examples.