getJson()関数は v0.1.0 で廃止されました。getJson() と同等の機能を備えた loadData() 関数の提供が、 v0.1.1 にて予定されています。

それまでの間は、代替手段として、関数型コンポーネントを宣言して使うことができます。

# A page with custom fetch function

This is a demo page with custom fetch function.

import { useState, useEffect } from 'react';

export const ComponentWithFetch = () => {
  const [data, setData] = useState(undefined);
  
  const execFetch = async () => {
  	const response = await fetch('https://api.example.com/v1/some_endopoint')
  	setData(response.data);
  }
  
  useEffect(() => {
  	execFetch();
  }, [])
  
  return (
  	<div>{ JSON.stringify(data) }</div>
  )
}

getJson() 関数は、Morphのデータ取得関数の1つです。aliasで指定された処理が、SQLや、DataFrameを返すPythonの関数の場合、その結果をJSON形式で取得することができます。

index.mdx
# Employee Data

export const employeeData = getJson({
  alias: 'employee_data_py'
});

## We have {value(employeeData).length} employees.

getJsonの返り値

getJsonの返り値は、次のような構造を持っています。

response

{
  "data": {
    "type": "json",
    "data": ...
  },
  "error": Error | undefined,
  "loading": boolean
}

data.data の中には、Python関数やSQLファイルの実行結果が入っています。

getJsonの結果を表示する

getJson() の返り値は、value() 関数を使って取り出すことができます。

index.mdx
export const employeeData = getJson({
  alias: 'employee_data_py'
});

{ JSON.stringify(value(employeeData).data) }
{}で囲まれた内容は、JSXのノードとして評価されるため、string, boolean, number, null, undefined, またはReactコンポーネントのいずれかである必要があります。ここでは、 JSON.stringify() を用いて文字列化しています

variableを使う

getJson() は、データコンポーネントと同様にvariableを使うことができます。

index.mdx
export const depertment = variable();

<VariableInput variable={depertment} />

export const employeeData = getJson({
  alias: 'employee_data_py',
  variables: {
    department: depertment
  }
});

## We have {value(employeeData).length} employees in { value(department) } department