Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 974
user15322469 Avatar asked Jul 08 '26 03:07

user15322469


1 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.

like image 114
Heretic Monkey Avatar answered Jul 09 '26 16:07

Heretic Monkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!