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

165
Visualizações
Uncaught TypeError: Cannot read properties of undefined (reading '0') at line 13:1

while working on code ran into some errors on line 13 when the value is undefined and is reading as 0 please how can I solve this

the error message

homepage.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '0')

  const dispatch = useDispatch();
  const danceClass = useSelector((state) => state.class);
  const { classes } = danceClass;

  const [dance, setDance] = useState(
    classes[0] ? classes[0].slice(0, 3) : [],
  );
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If your danceClass object doesn't have a classes property, then classes will be undefined and classes[0] will produce the error you're seeing.

Try using optional chaining instead

const [dance, setDance] = useState(classes?.[0]?.slice(0, 3) ?? []);

The above will also work if classes is an empty array.

about 4 years ago · Juan Pablo Isaza Relatório

0

Because the classes is undefined. You should check like

classes ? classes[0]?.slice(0,3) : []
about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest you to use fallbacks for possibly undefined values for instance

  const dispatch = useDispatch();
  const danceClass = useSelector((state) => state?.class ?? {});
  const { classes = [] } = danceClass;

  const [dance, setDance] = useState(
    classes[0]?.slice(0, 3) ?? [],
  );

Like that, you are going to check whather or not state.class is a nullish value, if it's nullish, with the use of nullish coaleascing operator you are going to assign an empty object.

Then, when destructuring for classes, if danceClass is an empty object without the property classes, what you're getting is a variable classes initialized as an empty array.

Then again, with the use of chaining operator in classes[0]?.slice(0, 3) you're checking if the first element is nullish, (through the optional chaining operator) if this is your're going to set the dance variable as an empty array again with the use of nullish coaleascing operator

about 4 years ago · Juan Pablo Isaza 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