I am fetching data from github's api using fetch and would like to use the results in the document title, initially this works in development but on manual page reload I get an error. How can I correctly insert data.name into the document title?
react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of null (reading 'name')
useEffect( () => {
if ( !login ) return;
setLoading( true );
fetch( `https://api.github.com/users/${login}` )
.then( ( response ) => response.json() )
.then( setData )
.then( setLoading( false ) )
.catch( setError )
}, [login] );
useEffect(() => {
document.title = `Congratulations ${data.name}'s on Learning React`;
}, [])
You can use the react-helmet Library, this is a must famous library to manipulate head tags of your document!
Note: the error in your console occured because your state data
is not an object, and you are trying get the key name
.
This is the same of:
null.name
Note that, null
is the first value of your state, and to get the name
of null
is not possible!