Issue
i want to push an object into an empty array in useMemo method using typescript. i have code like below,
const commonDetails = data?.CommonDetails;
const details: Details[] = [];
const selectedItems = React.useMemo(() => { // here selectedItems type is set to
// number or undefined. instead i expect it to be of type Details[] too as i push
// commonDetails which is an object into details which is array.
return commonDetails && details.push(commonDetails);
}, [commonDetails]);
console.log('selectedItems', selectedItems); //this outputs 1. but i expect an array
// of object
could someone help me with this. i am not sure why the selectedItems is number instead of array of object. thanks
Solution
The Array.push()
method adds one or more elements to the end of an array and returns the new length of the array.
const selectedItems = React.useMemo(() => {
return commonDetails? [...details, commonDetails] : [];
}, [commonDetails]);
If commonDetails
is an array
, [...details, ...commonDetails]
Hope this would be helpful for you.
Answered By - Bikas Lin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.