LoginSignup
2
4

More than 5 years have passed since last update.

GASのWebAPIをReactで取得

Posted at

概要

GASでWebAPIを公開して、Reactで取得します。

参考

Web API作成(Get)

  1. Googleアカウントにログインして、スプレッドシートを作成する。https://docs.google.com/spreadsheets/
    image.png

  2. スプレッドシートにデータを入力する
    image.png

  3. ツール-スクリプトエディタを起動する
    image.png

  4. doGet(e)関数を実装する
    image.png

  5. ウェブ アプリケーションとして導入する
    image.png

  6. ブラウザからURLにアクセスして動作確認
    image.png

  7. Reactで取得

https://qiita.com/y_ohr/items/09e8b3983fbca7c02a23 にて、クラスのプロパティで保持していたデータを、Web APIからの取得に置き換え。
Web APIのURLはぼかしています。

App.tsx抜粋
private expressions: Expression[] = [
    /*
    new Expression(0, 0, Operator.plus, 1),
    new Expression(1, 2, Operator.minus, 3),
    new Expression(2, 4, Operator.times, 5),
    new Expression(3, 6, Operator.divide, 7),
    */
];

public constructor(props: any) {
    super(props);
    this.state = {
        list: this.expressions
    };

    this.handleXChange = this.handleXChange.bind(this);
    this.handleOChange = this.handleOChange.bind(this);
    this.handleYChange = this.handleYChange.bind(this);

    fetch('https://script.google.com/macros/s/***/exec')
        .then(response => response.json())
        .then(data => data.map((d: Expression) => new Expression(d.n, d.x, d.o, d.y)))
        .then(e => this.expressions = e)
        .then(() => { this.setState({ list: this.expressions }); });
}

感想

  • Reactでサーバと通信できた
  • 更新(doPost())もやってみたい
  • fetch()promise()は、もう少しこなれた書き方はできないか?
  • TypeScriptの: typeas typeが混同する
  • TypeScriptのnumber + numberがstringのコンカチになった

以上

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4