I am new to React/Typescript and I am trying to create a loading page before rendering some orders I have the following main class OrderUi:
const OrderUi = () => {
const [loading, setLoading] = React.useState(false as boolean);
return (
<table>
{loading ?
orders.map((order: Order, key: number) => (
<OrderOverview key={key} order={order} setLoading={setLoading}/>
)) : <LoadingPage />}
</table>
);
export {OrderUi};
This is my OrderOverview
interface OrderOverviewProps {
setLoading: (loading: boolean) => void;
}
export const OrderOverview = (props: { order: Order } & OrderOverviewProps) => {
props.setLoading(true);
return (
<tr key={props.order.orderNumber}>
<td>
<span>{props.order.timestamp.toString().substring(0, 10)}<br/>
{props.order.timestamp.toString().substring(11, 16)}</span>
</td>
<td>
<div>
<p><span>{props.order.orderNumber}</span></p>
<a className="detailsLink keyNav-element">Details</a>
</div>
</td>
</tr>
);};
And this is LoadingPage
const LoadingPage = () =>
(
<div>
<p>Loading</p>
</div>
);
export {LoadingPage};
I don't know if my logic is correct, I still receive the loading=false and I hope you could give me some advices of what can I do
You can use useEffect
hook for that:
const OrderUi = () => {
const [loading, setLoading] = React.useState(true as boolean);
const [orders, setOrders] = React.useState([] as Order[]);
React.useEffect(() => {
if (orders.lenght > 0) {
setLoading(false);
}
}, [orders]);
return (
<table>
{!loading ?
orders.map((order: Order, key: number) => (
<OrderOverview key={key} order={order} />
)) : <LoadingPage />}
</table>
);
}
export { OrderUi };