Home > OS >  react typescript object is possible undefined
react typescript object is possible undefined

Time:05-04

In my react typescript project I am trying to update a value in my redux state.

When I try to update the x1.quantity, I get the following error. (VS code puts a red line under x1)

Object is possibly 'undefined'

mySecondTest: (state, action: PayloadAction<TradeData>) => {
  console.log("this is mySecondTest reducer");
  console.log(action.payload);
  console.log(state.trades);

  const x1 = state.trades.find((item) => item.bbsymbol === "ADH2 Curncy");
  console.log("this is x1");
  if (x1.quantity !== undefined) {
    x1.quantity = 999;
  }

Can someone show me the proper way to handle this?

CodePudding user response:

There is an error because find can return undefined if no value was found. And to fix this there are many ways!

  1. Using optional chaining:

    if (x1?.quantity !== undefined) {
    
  2. Using && short-circuiting:

    if (x1 && x1.quantity !== undefined) {
    
  3. Using an assertion (! - only use if you are sure it can't be undefined):

    if (x1!.quantity !== undefined) {
    
  • Related