LoginSignup
43
44

More than 5 years have passed since last update.

【react】fetch apiを使ってjsonデータを取得、POSTでフォームデータを送信する

Posted at

ReactでMySQLに接続してデータを書き込みたい

初心者です。
まずは、Jsonデータを取得して表示までをやってみる。

まずはJsonでデータを取得して表示してみる。


  constructor(props) {
    super(props);
    this.state={
      loading: false
    };
  }

  componentDidMount(){
    return fetch('url')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          loading: true,
          data: responseJson,
        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render() {
    if(this.state.loading){
      return(
        <div className="App-header">
          <p>{ this.state.data }</p>
        </div>
      );
    }else{
      return(
        <div className="App-header">
          <p>Loading...</p>
        </div>
      );
    }
  }
}

はまったポイント
JsonのLoading中に、response.jsonの中身をrenderしようとすると、無理!っておこられる。
-> constructorのthis.state内でloading: falseを設定し、falseなら'Loading...'をrender、responseが帰って来たらloading: trueをsetStateして解決。
できたので、今度はPHPに送信してみる。

Fetchを使ってPHPにデータをPOSTで送信してみる

  onClickHandler = (e) => {
    e.preventDefault();
    const method = "POST";
    const body = new FormData(document.getElementById('form'));

    return fetch('url', {
      method,
      body
    })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          inputText:''
        });
        console.log(responseJson);
      })
      .catch((error) =>{
        console.error(error);
      });

  }
<?php

  $data = $_POST["text"];
  header('Access-Control-Allow-Origin:http://localhost:3000');
  header('Content-type: application/json');
  echo json_encode( $data );

いつも通り作ったフォームを、new FormDataでフォームデータ化。
fetch('url')にオプションをつけて、methodとbodyを与えてあげる。

43
44
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
43
44