Home > OS >  How to add an object to an empty array using typescript in useMemo react?
How to add an object to an empty array using typescript in useMemo react?

Time:11-10

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

CodePudding user response:

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.

CodePudding user response:

push return count const commonDetails = data?.CommonDetails;

const details: Details[] = [];

const selectedItems = React.useMemo(() => { 
    return commonDetails ? [ ...details, commonDetails] : [];
}, [commonDetails, details]); // this will most likey need the dependencies

details array might need to be included if it is a prop

CodePudding user response:

Two things to note here:

  1. .push() returns the new length of the array after pushing.

  2. The AND(&&) operator preserves non-Boolean values and returns them as they are. && evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

With the above in mind, one can understand why the below statements log what they do:

console.log({} && [2].push(5)); //2
console.log(true && [].push(5)); //1

Similarly,

return commonDetails && details.push(commonDetails);

will return 1 (if details is empty initially and commonDetails is truthy).

You can change your code like:

const selectedItems = React.useMemo(() => { 
  if(commonDetails) return [...details,commonDetails];
  return details;
}, [commonDetails]);

Also, try to not mutate and create new references.

  • Related