LoginSignup
3
2

More than 5 years have passed since last update.

【React】FetchAPIを使った非同期通信のやり方

Posted at

ReactでFetchAPIを使って非同期通信するフォームを作る方法をまとめておきます。

    class doSomethingButton extends React.Component{
        render(){
            return (
                <form id="do_something" onSubmit={
                    function(){
                        fetch(url, {
                            method: 'POST',
                            body: 'test'
                        })
                        .then(response => {
                            if (!response.ok) {
                               // 失敗時の処理
                            }
                        })
                    }}
                >
                <button type="submit">
                    卍ここ押すと非同期通信卍
                </button>
                </form>
            )
        }
    }

    ReactDOM.render(
        <doSomethingButton />,
        document.getElementById('hoge')
    );

解説

  • class dosomethingはReactコンポーネントで、ReactDOM.renderによって描画してほしい要素とその動作を定義する
    • render(){return( hogehoge )}といったふうに
    • ボタンを押したときやフォーム送信したときの動作は要素のonClickやonSubmitなどに定義する
  • 非同期通信はFetchAPIを使った
    • jqueryの$.ajaxに使い方が似ているが、done()やfail()はないので!response.okでエラーハンドリングする
3
2
2

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
3
2