[¿Cómo puedo pintar e incluir una carga simple hasta dos segundos después de que se represente el componente Item.js? He intentado hacerlo con condicionales pero no encuentro la forma
¿Debo hacer un condicional creando un estado y haciendo referencia a si el estado es verdadero o falso ejecutar el mapa en la matriz de estado de mambo? ]
const ItemList = () => { const [collection, setCollection] = useState([]); const [mambos, setMambos] = useState([]); useEffect(() => { const promesa = new Promise((resolve, reject) => { setTimeout(() => { if (id === "1") { resolve(PRODUCTS[0]); } else if (id === "2") { resolve(PRODUCTS[2]); } else if (id === "3") { resolve(PRODUCTS[1]); } else if (id === "4") { resolve(PRODUCTS[3]); } else if (id === "5") { resolve(PRODUCTS[4]); } else { reject( "Hubo un problema con la carga de elementos, intentalo mas tarde..." ); } }, 2000); }); promesa .then((rta) => { setMambos(rta.items); setCollection(rta); }) .catch((err) => err); }, [id, mambos, collection]); return ( <div> <h1 > <CollectionTitle /> </h1> {mambos.map(({ id, ...otherProps }) => <Item key={id} {...otherProps} />) )} </div> ); };hacer un estado [loading, isLoading] = useState(false)
establezca la carga como verdadero si se obtienen datos y si no solo se procesan
<p>loading...</p>
const ItemList = () => { const [collection, setCollection] = useState([]); const [mambos, setMambos] = useState([]); cosnt [loading, setLoading] = useState(false); useEffect(() => { const promesa = new Promise((resolve, reject) => { //when the data is being fetched we will show the loading sign setLoading(true); setTimeout(() => { if (id === "1") { resolve(PRODUCTS[0]); } else if (id === "2") { resolve(PRODUCTS[2]); } else if (id === "3") { resolve(PRODUCTS[1]); } else if (id === "4") { resolve(PRODUCTS[3]); } else if (id === "5") { resolve(PRODUCTS[4]); } else { reject( "Hubo un problema con la carga de elementos, intentalo mas tarde..." ); } }, 2000); }); promesa .then((rta) => { setMambos(rta.items); setCollection(rta); setLoading(false); }) .catch((err) => err); }, [id, mambos, collection, loading]); return ( <div> <h1 > <CollectionTitle /> </h1> {loading && <p>Loading...</p>} {!loading && mambos.map(({ id, ...otherProps }) => <Item key={id} {...otherProps} />) )} </div> ); };