ohacのブログ

React hooks collection vol.1 (MPChainの情報表示)

December 25, 2020

Monacoinの情報を取得して表示

クラスを使うのをやめてReact hooksを使うようにして作成しました。

mpchain.infoの公開APIを使ってMonacoinの情報を表示するコンポーネントです。

<MPChain />

このように書くと以下のように表示されます。

Connecting...

ソースコード

import React, { useEffect, useState } from "react"

function useMPChain() {
  const [mpchain, setMpchain] = useState(null);
  useEffect(() => {
    if (mpchain === null) {
      fetch('https://mpchain.info/api/cb')
        .then(res => res.json())
        .then(
          (json) => {
            setMpchain(json);
          },
          (error) => {
            console.log(error);
          })
    }
  });
  return mpchain;
}

export default function MPChain(props) {
  const mpchain = useMPChain();
  if (mpchain !== null) {
    const lastblk = mpchain['counterparty-server_last_block'];
    const index = lastblk.block_index;
    const difficulty = lastblk.difficulty;
    const hash = lastblk.block_hash;
    const time = lastblk.block_time;
    const date = new Date(time * 1000);
    const datestr = date.toLocaleString('ja-JP', { timeZone: 'JST' });
    return (
      <>
        <table>
          <tbody>
            <tr>
              <th>ブロックハッシュ</th>
              <td>{hash}</td>
            </tr>
            <tr>
              <th>採掘難易度</th>
              <td>{difficulty}</td>
            </tr>
            <tr>
              <th>ブロック高</th>
              <td>{index}</td>
            </tr>
            <tr>
              <th>日時</th>
              <td>{time} ({datestr})</td>
            </tr>
          </tbody>
        </table>
      </>
    );
  }
  return (
    <>Connecting...</>
  );
}