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

188
Views
Setting document title after api call in React

I'm trying to set the document title after making an API call and getting a response. However, I get the following error:

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'rendered')

I know why the error is occurring; It tries to access the API response (blogPost.title.rendered) before the response is returned. I'm just not sure why it's doing that and how to fix it. Here is my code:

import React, { useState, useEffect } from 'react';
import '../css/styles.css';
import { useParams, useLocation } from 'react-router-dom';
import dgAPI from '../cms/DGAPI';

const BlogPost = () => {
    const [loading, setLoading] = useState(true);
    const [blogPost, setBlogPost] = useState({});

    let blogPostURL = dgAPI.getPostFromSlug + useParams().slug;

    const getPost = async () => {
        // Fetch blog post
        fetch(blogPostURL)
            .then(response => response.json())
            .then(post => {
                setBlogPost(post[0]);
                setLoading(false);
            }).then(() => {
                document.title = blogPost.title.rendered;
            })
    }

    useEffect(() => {
        getPost();
    }, []);

    return (
        <>
            ...
        </>
    )
}

export default BlogPost

I have also tried the following but had no luck:

import React, { useState, useEffect } from 'react';
import '../css/styles.css';
import { useParams, useLocation } from 'react-router-dom';
import dgAPI from '../cms/DGAPI';

const BlogPost = () => {
    const [loading, setLoading] = useState(true);
    const [blogPost, setBlogPost] = useState({});

    let blogPostURL = dgAPI.getPostFromSlug + useParams().slug;

    const getPost = async () => {
        // Fetch blog post
        const response = await fetch(blogPostURL);
        const post = await response.json();
        setBlogPost(post[0]);
        document.title = blogPost.title.rendered;
        setLoading(false);
}

useEffect(() => {
    getPost();
}, []);

return (
    <>
        ...
    </>
)
}

export default BlogPost

I'm not sure why it won't wait to receive the response before it sets the document title.

Any help is much appreciated!

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!