Why isn't my document title property being updated?

Viewed 91

In my project, when I am unable to change document.title (the title of the document) after fetching data through API. My code is as follows:

useEffect(() => {
        loadData();
        console.log(name)
        document.title = `${name}`
    }, []);

const loadData= async () =>  {
axios.get('https://api.themoviedb.org/3/movie/' + props.match.params.id + '?api_key=***').then(
            res=>{
                setName(res.data.title)}

 
        )}

However, the console.log does correctly show the name. How to fix this?

2 Answers

To change the title based on changes to the name, you can create a separate useEffect hook and put name in the dependency array.

React.useEffect(() => {
  document.title = name;
}, [name]);

Here you are using [] only watcher in useEffect, this code will render only one time, if you want to change the document.title please modify the code too

useEffect(() => {
document.title = name
},[name])

[name] this means whenever the state change this useEffect will trigger

Related