Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!