Search code examples
javascriptreactjsfetch

Exception for null fetched data React


I am mapping fetched data like this in React. I am printing name, column and row to the paragraph so whenever it is null, it prints just null null null, but if warehouse_name is null I need to transfer all values to some String like "Undefined" instead of these tree null.

There can be maybe better solution with using some string method for paragraph instead of this?

  const transformedData = data.order_items.map((invoiceData) => {
    return {
      alternative_warehouse_position: invoiceData.alternative_warehouse_position,
      warehouse_column: invoiceData.warehouse_column,
      warehouse_name: invoiceData.warehouse_name,
      warehouse_row: invoiceData.warehouse_row,
    };

Solution

  • 3 ways to do it:

    • Using the "?" to check if its null. Example: ${Condition} ? ${is true} : ${is false}.

    • Using the new null-checking syntax. Example: ${Value} ?? ${the replacement if its null}

    • Using the OR operator, which enhances backwards capabilities. Example: ${first condition} || ${Second to replace if the first is false}

    Note: Null counts as false