I'm tring to use 'React-Select' for my WordPress block component to select post categories.
What I want is to display 'Loading...' while loading categories and then display the categories list or 'No Categories Found' when loading is complete.
With my code, it displays 'No Categories Found' while loading, then displays categories list.
export default class Categories extends Component {
constructor() {
super( ...arguments );
this.state = {cats: []};
}
componentDidMount () {
return apiFetch({path: '/myoriginal-blocks/v1/categories'})
.then(data => {
this.setState({cats:data});
})
}
onChangeCategories = newCategories => {
this.props.setAttributes({ category: newCategories == null ? [] : newCategories });
}
render() {
const { attributes } = this.props;
const { category } = attributes;
return (
<>
<div>
<label>Categories</label>
<Select
isMulti
isClearable
placeholder='Search categories...'
onChange={ this.onChangeCategories }
options={ this.state.cats }
value={ category && category }
noOptionsMessage={() => 'No Categories Found'}
/>
</div>
</>
);
}
}

Or maybe I have to use 'Async-Select' instead of 'React-Select' but I could not understand well it's documentation.
https://react-select.com/async
Hope someone help me. Thank you.
You can you isLoading prop of react-select component.
add a property in your state to manage loading
this.state = {cats: [], isLoading: true};
and then set isLoading false
return apiFetch({ path: "/myoriginal-blocks/v1/categories" }).then(
(data) => {
this.setState({ cats: data, isLoading: false });
}
);
and in Select component pass the isLoading prop
<Select
isMulti
isClearable
placeholder='Search categories...'
onChange={ this.onChangeCategories }
options={ this.state.cats }
value={ category && category }
noOptionsMessage={() => 'No Categories Found'}
isLoading={this.state.isLoading}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With