node上のpod一覧を表示する画面を作成する ~ (2) Reactで画面を作成 ~
前回の記事の続きです。 React触ってみました。
axiosで前回作成したサーバに対してAPIリクエストし、node情報を取得する
定数(server)にaxios.createをセットすることで、複数axios.createを定義できるようにしました。
api/http-common.tsx
const server = axios.create({ baseURL: "http://localhost:8090/v1", headers: { "Content-type": "application/json", } }) const httpObject = { server } export default httpObject
apiリクエスト。Typescriptでレスポンスの型を定義できるのは良いですね。
api/api.tsx
export interface nodeDescribeInf { nodes: node[] } export interface node { name: string pods: pod[] } interface pod { namespace: string name: string } const nodeDescribe = () => { return http.server.get<nodeDescribeInf>("/node/describe"); }
レスポンス結果がうまくレンダリングされなかったので、修正
はじめのレンダリング時に、dataにデフォルトの値がなかったのが原因?
デフォルト値をセットすることで、axiosで非同期に取得されdataにセットされた値がレンダリングされる。
状態の管理のためにuseStateを使うのが基本のようです。
var ndInf : nodeDescribeInf | undefined const [data, setData] = useState(ndInf) Api.nodeDescribe().then( ( response ) => { setData(response.data) } ).catch( err => console.log(`Error: ${err}`) ) . . . <div className="dashboard"> { data && data.nodes.map((v,i) => <Node podNum={v.pods.length} nodeName={v.name} key={i}/> ) } </div>
起動したところ、無限にAPIリクエストが実行されてしまう、、、
debugのためにconsole.logを仕込みました。
const nodeDescribe = () => { console.log("responder"); return http.server.get<nodeDescribeInf>("/node/describe"); }
renderの中でuseStateしてstateを更新しているからのよう。
useEffect(...,[])を使用して、最初のレンダリング時のみAPIリクエストを行うようにしました。
useEffect(() => { Api.nodeDescribe().then( ( response ) => { setData(response.data) } ).catch( err => console.log(`Error: ${err}`) ) },[])
期待通り画面が表示されました。
それぞれのnode上に起動しているpodsを表示しています。