Tengo una página donde una api se carga lentamente y solo se muestran dos botones en mi página durante algunos segundos, así que decidí agregar un cargador en esa página. Probé el código a continuación, pero el cargador está cargado, no la tabla de páginas.
import Loader from '../Loader/Loader'; const FileTable = () => { const [isVisible, setIsVisible] = useState(true); const handleLoading = () => { setIsVisible(false); } useEffect(() => { window.addEventListener("load",handleLoading); return () => window.removeEventListener("load",handleLoading) },[]) return !isVisible ? ( <div> My component </div> ):( <div> <h1>Loading...</h1> </div> ) } export default FileTable;Incluso probé el siguiente código
const [isVisible, setIsVisible] = useState(false);y entonces
if(!isVisible){ return <>Loading</> } return( <> My Component </> )He probado de las dos maneras pero el cargador no funciona. Los botones también deben ocultarse cuando se carga la página, solo se debe mostrar el cargador hasta que se cargue la API. ¿Cómo lo soluciono?
Un escenario simple y directo sería:
Un ejemplo de código sería el siguiente:
const MyComponent = () => { const [loading, setLoading] = useState(true); const [apiData, setApiData] = useState([]); // or whatever const handleClose = () => { setLoading(false) } useEffect(() => { // Init API call here // then( ..... setApiData()) // Do whatever with API response to set component apiData // finally (() => setLoading(false)) }, []) // empty dependency array is equivalent to componentDidMount if(loading) { return <Loader /> } return <Component data={apiData} /> }También es una buena práctica manejar eventuales fallas de llamadas a la API.