'Gutenberg Infinite Loop

I'm working on building a Gutenberg block but it seems I keep getting an infinite loop. How can I invoke the rest API only once?

I am trying to get a list of officers - custom post type - but as the initial call doesn't provide the featured image I thought I should loop through and add the images "manually". If there is a better approach please do let me know.

registerBlockType('test/officers-block', {
    title: __('Officers Block', 'test'),
    description: __('Block to generate the officers block', 'test'),
    icon: '',
    category: 'test',

    attributes: {
        title: {
            type: 'string',
        },
        posts: {
            type: 'array',
        }
    },

    edit: ({ attributes, setAttributes }) => {

        const {
            title,
            posts,
        } = attributes


        // Request data
        const data = useSelect((select) => {
            return select('core').getEntityRecords('postType', 'officers', { per_page: -1 });
        });

        const isLoading = useSelect((select) => {
            return select('core/data').isResolving('core', 'getEntityRecords', [
                'postType', 'officers',
            ]);
        });

        const setOfficers = ( data ) => {
            let officerData = [];
            data.map(( officer ) => {
                wp.apiFetch( { path: '/wp/v2/media/' + officer?.featured_media } ).then( function( image ){
                    officerDataEach.title = officer?.title?.rendered
                    officerDataEach.content = officer?.content?.rendered
                    officerDataEach.job = officer?.meta?._job_title
                    officerDataEach.phone = officer?.meta?._phone
                    officerDataEach.email = officer?.meta?._email
                    officerDataEach.image = image?.media_details?.sizes?.full?.source_url
                    officerData.push( officerDataEach )
                })
            })
            console.log(officerData);
            setAttributes( { posts: officerData } )
        }

        if( !isLoading && data ){
            setOfficers( data );
        }


        if ( isLoading && !data ) {
            return <h3>Loading...</h3>;
        }
    ...

Thanks in advance


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source