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

173
Visualizações
React "Cannot read properties of undefined" on an object

I'm guessing the problem is about it being async, and it tries to read it before the data is fetched, but that shouldn't happen. This code is same as on every tutorial. I thought useEffect and .then() are handling this. What's the problem here ? Actually on tutorials they access the data with categories.title directly, without even using categories[0]. I'm confused.

import React, { useState, useEffect } from "react";
import { useOutletContext } from "react-router-dom";
import Birimler from "../../components/birimler";
import sanityClient from "../../Client";
const Yasambilim = () => {
  const { setTitle } = useOutletContext();

  useState(() => {
    setTitle("YAŞAMBİLİM");
  }, []);

  const [categories, setCategories] = useState([]);
  
  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "article"]{
        title,
        slug,
      }`
      )
      .then((data) => setCategories(data))
      .catch(console.error);
  }, []);

  console.log(categories); /* prints [{…}] */
  console.log(categories[0]); /* prints {slug: {…}, title: 'Test Title'} */
  console.log(
    categories[0].title
  ); /* app crashes  Cannot read properties of undefined (reading 'title') */

  return (
    <>
      <Birimler />
    </>
  );
};
export default Yasambilim;
about 4 years ago · Juan Pablo Isaza
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