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!