HarshvardhanSharma
HarshvardhanSharma

Reputation: 786

Immutable.js conditionally update Map

const state = fromJS({
  poolName: {
    poolNameCost:
    poolNamePercentage:
    poolNameShare:
  }
})

where poolName varies across actions.

I have to update all the properties poolNameCost, poolNamePercentage, poolNameShare if either of it updates.

I do

const { poolName, val, fieldSuffix, initialCost, initialShare } = action.payload;
state.update(`${poolName}`,
  items => ({
    ...items,
    [`${poolName}Cost`]() {
      if (suffix === 'Share') return (val / initialCost) * initialShare;
      if (suffix === 'Percentage') return (val / initialCost) * 100;
      return val
    },
    [`${poolName}Share`]() { //.....// },
    [`${poolName}Percentage`]() { //.....// },
  })
)

I get an empty object poolName = {}. Why does this happen?

The code above is a refactored version of the code below, that works well.

Code,

 (suffix === 'Cost') &&
 state.update(`${poolName}`,
  items => ({
    ...items,
    [`${poolName}Share`]: (val / initialCost) * initialShare,
    //...similarly for other sibling property of `Share` in `poolName`...//
  })
 )

values correctly update.

Upvotes: 1

Views: 251

Answers (1)

HarshvardhanSharma
HarshvardhanSharma

Reputation: 786

The lines

[`${poolName}Cost`]() {
      if (suffix === 'Share') return (val / initialCost) * initialShare;
      if (suffix === 'Percentage') return (val / initialCost) * 100;
      return val
}, 

in code when invoked returned the functions themselve. So I changed them into IIFE, like this

[`${poolName}Cost`]: (function() {
      if (suffix === 'Share') return (val / initialCost) * initialShare;
      if (suffix === 'Percentage') return (val / initialCost) * 100;
      return val
})(),

Now it returns the underlying value after evaluation.

Is there a better way to achieve the result?

Upvotes: 1

Related Questions