Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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): []
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda