wp-matchplay/src/edit.js

102 lines
3.0 KiB
JavaScript

import {InspectorControls, useBlockProps} from '@wordpress/block-editor';
import {TextControl, PanelBody} from '@wordpress/components';
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}) {
function fetchTournamentData() {
const headers = {
"Authorization": `Bearer ${attributes.matchplay_api_key}`,
"Content-Type": "application/json",
"Accept": "application/json",
};
const tournamentUrl = new URL(`https://next.matchplay.events/api/tournaments/${attributes.tournament_id}`);
const standingsUrl = new URL(`https://next.matchplay.events/api/tournaments/${attributes.tournament_id}/standings`);
const params = {
"includePlayers": "1",
"includeArenas": "0",
"includeBanks": "0",
"includeScorekeepers": "0",
"includeSeries": "0",
"includeLocation": "1",
"includeRsvpConfiguration": "0",
"includeParent": "1",
"includePlayoffs": "1",
"includeShortcut": "0",
};
Object.keys(params).forEach(key => tournamentUrl.searchParams.append(key, params[key]));
// get players
fetch(tournamentUrl, {method: "GET", headers})
.then(response => response.json())
.then(response => {
let newData = {...response};
setAttributes({data: {players: newData}});
console.log(newData);
})
.catch(err => console.error(err));
// get standings
fetch(standingsUrl, {method: "GET", headers})
.then(response => response.json())
.then(response => {
let newData = {...response};
setAttributes({data: {standings: newData, ...attributes.data?.players}});
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>
{attributes.data?.players && attributes.data?.standings && (
<>
<table id="tournament-results-table">
<thead>
<tr>
<th>Place</th>
<th>Player</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{Object.keys(attributes.data.standings).map((player, i) => {
return (
<tr key={player}>
<td>{attributes.data.standings[i].position}</td>
<td>{attributes.data.players.find(p => p.playerId === attributes.data.standings[i].playerId).name}</td>
<td>{attributes.data.standings[i].points}</td>
</tr>
);
})}
</tbody>
</table>
</>
)}
</div>
</>
);
}