wp-matchplay/src/edit.js

73 lines
1.9 KiB
JavaScript

import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { TextControl, PanelBody } from '@wordpress/components';
import { useState } from '@wordpress/element';
import './editor.scss';
/**
* The edit function describes the structure of your block in the context of the
* editor. This represents what the editor will render when the block is used.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
*
* @return {WPElement} Element to render.
*/
export default function Edit( { attributes, setAttributes } ) {
const [apiData, setApiData] = useState(null);
function fetchTournamentData() {
let url = `https://matchplay.events/data/tournaments/${attributes.tournament_id}/standings`;
fetch(url)
.then(response => response.json())
.then(response => {
let newData = { ...response };
setAttributes( { data: newData } );
setApiData(newData);
console.log(newData);
})
.catch(err => console.error( err ));
}
return (
<>
<InspectorControls>
<PanelBody>
<TextControl
label="Tournament ID"
value={ attributes.tournament_id }
onChange={ val => setAttributes( { tournament_id: val } ) }
/>
</PanelBody>
</InspectorControls>
<div { ...useBlockProps() }>
<p>Results for tournament id { attributes.tournament_id }</p>
<button onClick={() => fetchTournamentData()}>Fetch Results</button>
{apiData && (
<>
<table id="tournament-results-table">
<thead>
<tr>
<th>Place</th>
<th>Player</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{Object.keys(apiData).map((player, i) => {
return (
<tr key={player}>
<td>{apiData[i].position}</td>
<td>{apiData[i].name}</td>
<td>{apiData[i].points}</td>
</tr>
);
})}
</tbody>
</table>
</>
)}
</div>
</>
);
}