Home  Js   How to use ...

How to use optional chaining operator in JavaScript

Consider below line of code.

let { paid, price } = await getCourseBySlug(params.id[0]);

Here getCourseBySlug may return null so destructuring will fail. Because it tries to destructure properties from null, leading to an error. To handle this scenario, you can use conditional (optional) chaining and default values.

Here’s an example of how you can safely destructure the properties paid and price from the result of getCourseBySlug while handling the case where it returns null:

Using Optional Chaining and Default Values

let course = await getCourseBySlug(params.id[0]);
let { paid = false, price = 0 } = course || {};

Explanation

  1. Fetch the Course: Use await to fetch the course.
  2. Optional Chaining: Use course || {} to provide a default empty object in case course is null.
  3. Destructuring with Default Values: Destructure paid and price from the course object, providing default values (false for paid and 0 for price) in case they are undefined.

Full Example

Here’s a full example to illustrate this in context:

async function fetchCourseDetails(slug) {
  try {
    let course = await getCourseBySlug(slug);
    let { paid = false, price = 0 } = course || {};

    console.log(`Course Paid: ${paid}, Course Price: ${price}`);
  } catch (error) {
    console.error('Error fetching course details:', error);
  }
}

// Usage
fetchCourseDetails(params.id[0]);

Additional Error Handling

You might also want to handle cases where getCourseBySlug throws an error:

async function fetchCourseDetails(slug) {
  try {
    let course = await getCourseBySlug(slug);
    if (!course) {
      console.log('Course not found');
      return;
    }
    let { paid = false, price = 0 } = course;

    console.log(`Course Paid: ${paid}, Course Price: ${price}`);
  } catch (error) {
    console.error('Error fetching course details:', error);
  }
}

// Usage
fetchCourseDetails(params.id[0]);

This way, you ensure that your code handles the null case gracefully, preventing runtime errors caused by trying to destructure properties from null.

Published on: Jul 27, 2024, 12:28 PM  
 

Comments

Add your comment