How can I use optional chaining in object data when I use JavaScript?

Viewed 771

I'm taking singlePost data from Redux and making it into an array using Object.keys.

However, when rendering is in progress, singlePost is received late, so when I try to console.log, null is recorded at first and then the correct data comes in.

So this error is printed.

Cannot convert undefined or null to object

this is my code

  const Explain = ({navigation, route}) => {
  const {singlePost} = useSelector((state) => state.post);

  console.log("singlePost:",singlePost);

  // singlePost: null    first recorded

  // singlePost:

  // singlePost = {
  //   User: {
  //     id: 3,
  //     nickname: "bill",
  //   },
  //   content1: "number1",
  //   content2: "number2",         second recorded
  //   content3: "bye",
  //   content4: "empty",
  //   content5: "empty",
  //   content6: "empty",
  //   content7: "empty",
  //   content8: "number3",
  //   content9: "empty",
  //   content10: "empty",
  // };   


  const contentOnly = Object.keys(singlePost)
  
  return (
  
  );
};

export default Explain;

    

How can I fix this error? Can I use optional chaining in object?

How can I fix my code?

3 Answers

There's no need for optional chaining. Optional chaining is only useful when accessing a property of a possibly-null object, and you're calling a function with the object as an argument.

You might be thinking of the nullish coalescing operator, which gives you a different value if the one under inspection is null or undefined, which you could possibly use here via:

const contentOnly = Object.keys(singlePost ?? {});

However, I'd say that's a rather roundabout way of getting an empty array. I'd just use a ternary, or conditional operator:

const contentOnly = singlePost == null ? [] : Object.keys(singlePost);

This tells readers exactly what they're going to get, especially if you set singlePost to null by default.

you can check the typeof the variable and whether it's null or not as below:

const contentOnly = (typeof singlePost === 'object' && singlePost !== null) ? Object.keys(singlePost): []

In your case you can check if singlePost is defined:

const contentOnly = Object.keys(singlePost || {})
// or
if(singlePost && typeof singlePost == 'object') {...do something}

If your need optional chaining(according to question title). You can do something like this

singlePost && singlePost.content1
// or with new syntax
singlePost?.content1

Pay attention - the new syntax is not supported by all environments

Related