You can use the displayLoadingIndicator
method available in SPFx. Using it you can show the loading indicator on a DOM element and clear it out using clearLoadingIndicator
method once the data is retrieved.
You can use the below sample code:
public render(): void {
// show indicator
this.context.statusRenderer.displayLoadingIndicator(document.getElementById("webpartId"), "Fetching list data");
pnp.sp.web.lists.getByTitle("Custom List").items.get().then(d => {
// clear indicator once the request is completed
this.context.statusRenderer.clearLoadingIndicator(document.getElementById("webpartId"));
console.log("List items fetched");
});
}
Reference - Taking Advantage of the Loading Indicator in the SharePoint Framework
Another option if you can choose is the Office UI Fabric's spinner component which can displayed or hidden based on the state.
You can modify from below sample code in React:
constructor() {
// code omitted for brevity
this.state = {
loading: true,
items: [],
error: null
}
}
private _fetchRecentDocuments() {
pnp.sp.web.lists.getByTitle("Custom List").items.get().then(items => {
this.setState({
loading: false,
listItems: items,
})
}).catch(d => {
this.setState({
loading:false,
error: JSON.stringify(d)
})
})
}
public componentDidMount(): void {
this._fetchListItems();
}
public render(): React.ReactElement<IRecentListItemsProps> {
return (
<div className={styles.helloWorld}>
{
this.state.loading && <Spinner label="Getting list data" size={SpinnerSize.medium} />
}
{
this.state.listItems && this.state.listItems.length > 0 ? (
<List items={this.state.listItems}
onRenderCell={this._onRenderCell} />
) : (
!this.state.loading && (
this.state.error ?
<span className={styles.error}>{this.state.error}</span> :
<span className={styles.nolistItems}>No documents found</span>
)
)
}
</div>
);
}
Reference - Office Fabric UI React Spinner component