import { useState, useEffect } from '@wordpress/element';
var pagelayer_posts_data = {};
var pagelayer_ajax_data = {};

export const RenderArchivePostsBlock = (props) => {
    const { _props, pl_props, tag, data } = props;
    const { id, atts } = data;
    const { attributes } = _props;
    const [response, setResponse] = useState('');

    useEffect(() => {
        var post = {};
        
		// All atts
        post['atts'] = JSON.parse(JSON.stringify(atts));
        post['atts']['pagelayer-id'] = id;
        post['pagelayer_nonce'] = pagelayer_ajax_nonce;

        if (pagelayer_empty(pagelayer_posts_data) || !pagelayer_compare_object(pagelayer_posts_data, post) || pagelayer_empty(pagelayer_ajax_data[id])) {
            pagelayer_posts_data = post;

            jQuery.ajax({
                url: pagelayer_ajax_url + 'action=pagelayer_archive_posts_data',
                type: 'post',
                data: post,
                success: function (data) {
					
                    var d = jQuery(data)
					d.children('style').remove();
					var html = d.html();
					
                    setResponse(html)
                    pagelayer_ajax_data[id] = html;
                }
            });
        }else{
            setResponse( pagelayer_ajax_data[id])
        }
    }, [attributes])

    return (
        <div dangerouslySetInnerHTML={{__html: response}} />
    )
}