Is it possible to use an array variable in the return section of the edit function of a Gutenberg block?

Viewed 22

I can fetch the data from WordPress using the REST API and display it in the SelectControl in the return section of the edit function like in the following:

attributes:
    {
        queryid:
        {
            type: 'string',
            default: '',
        },
        jsondata:
        {
            type: 'array'
        },
    },
    
    edit: ( { attributes, setAttributes, className } ) => {
        const fetchSearchQueries = async () => {
            const response = await fetch(`http://${ window.location.hostname }/corporagrid/wp-json/corpora/v1/query`, {
                cache: 'no-cache',
                headers: {
                    'user-agent': 'WP Block',
                    'content-type': 'application/json',
                },
                method: 'GET',
                redirect: 'follow',
                referrer: 'no-referrer'
            }).then(returned => {
                    if ( returned.ok ) {
                        return returned;
                    }
                    throw new Error( 'Network response was not ok.' );
                }
            );
            let searchQueries = await response.json();
            let searchQueriesArray = [];
            searchQueries.forEach( searchQuery => {
                searchQueriesArray.push( { value: searchQuery.id, label: searchQuery.name } );
            } );

            setAttributes( { jsondata: searchQueriesArray } );
        };
        fetchSearchQueries();
        return (
            <div className={ className }>
                <SelectControl
                    label={__('Selected Search Query:', 'test')}
                    options={ attributes.jsondata }
                    value={attributes.queryid}
                    onChange={(newval) => setAttributes({ queryid: newval })}
                />
            </div>
        );
    }

I had to set my array attribute to the array variable I created but actually I don't need to use this array attribute. Since I cannot use the array variable in the select control I found this solution. I receive undefined variable error when I use the array itself. Is there a way to accomplish this without setting the attribute to the array?

0 Answers
Related