Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Select : How to display 'Loading...' while loading options

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>
            </>
        );
    }
}

enter image description here

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.

like image 613
abms Avatar asked Feb 22 '26 16:02

abms


1 Answers

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}
/>
like image 146
Pranit Madhavi Avatar answered Feb 25 '26 12:02

Pranit Madhavi