'How can I paint and include a simple loading until the element component renders?
[How can I paint and include a simple load until two seconds after the Item.js component renders? I've tried to do it with conditionals but I can't find a way
should i do a conditional by creating a state and referring to whether state is true or false run the map on the mambo state array? ]
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>
);
};
Solution 1:[1]
make a state [loading, isLoading] = useState(false)
set loading true if data is fetched and if its not just render <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>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rahil Siddique |