Reputation: 107
so im creating a small webApp using reactjs with material ui, its basically the settings to customize the color, family, weight of any button or text so im using the Select to display a list of google font families and when the user picks one it gets added to the overall settings object when i click on the list it takes a few seconds(~4 to 8 to load Im not sure of the issue nor the solution. So i was wondering if this is due to my internet connection(3Mbs XD) or might it be something else. a solution may be setting the list to local storage then it only slow loads once or even have a local version of google fonts...
const [googleFonts, setGoogleFonts] = useState();
useEffect(() => {
let isMounted = true;
let cancelToken = axios.CancelToken.source();
const fetchData = async () => {
try {
let res = await client.get();
if (isMounted) {
setGoogleFonts(res.data.items);
}
} catch (e) {
console.error(e);
};
}
fetchData();
return () => {
isMounted = false;
cancelToken.cancel();
}
}, []);
<Select
labelId="FontFamily"
id="FontFamilySelect"
name="FontFamily"
style={{ width: '188px' }}
defaultValue='PT Sans'
value={widgetFont}
onChange={(e) => setWidgetFont(e.target.value)}
>
{googleFonts?.map((option, index) => (
<MenuItem key={index} value={option.family} >
{option.family}
</MenuItem>
))}
</Select>
Thank you
Upvotes: 0
Views: 250
Reputation: 4701
Follow this code, your UI render when font loaded
import React, { useEffect, useState } from 'react';
const MyComponent = ( ) => {
const [loading, setLoading] = useState(true);
useEffect( ()=> {
document.fonts.load("20px FontFamilyName").then( () => { setLoading(false) } );
}, [])
return (
<React.Fragment>
{ loading
? <div>Loading...</div>
: <main id="mainWrapper">
Reset of Eelements
</main>
}
</React.Fragment>
);
};
export default MyComponent;
Upvotes: 0
Reputation: 7680
I don't know about the internet connection, because your user experience could vary. But i think there's some issue in this code.
const [googleFonts, setGoogleFonts] = useState();
You code could break at the beginning, so it's better to anticipate some bad outcome. For example,
const [googleFonts, setGoogleFonts] = useState([]);
Make the initial value an array []
might help in your case.
Or add a spinner if it's not loaded try displaying something else.
The reason this is different than your case is that suppose your loading takes 1s. What the user do around that time? And more importantly your UI has to still functional, ex.
Select
is jammed during transition, i don't know.Upvotes: 1