LoginSignup
8
8

More than 5 years have passed since last update.

React (TypeScript): メモリリークしないaxiosの使い方

Posted at

Memory leakしないaxiosの使い方

ReactでAJAXのリクエストを送信する際にはwindow.fetch, jQuery AJAX, Axiosなど色々利用する事が可能です。

この記事ではAxiosを利用してmemory leakを起こさずに、AJAXのリクエストを送信する方法を記載します。

1. state用のインターフェースを定義する

import axios, { CancelTokenSource } from 'axios'

interface IState {
    source: CancelTokenSource
}

2. AxiosのCancelTokenSourcestateに保存する

class AxiosSample<{}, IState> extends React.Component {
    public state = {
        source: axios.CancelToken.source()
    }
    ...
}

2. AJAXコードの呼び出しは、componentDidMount()で行う

この際に{ cancelToken: this.state.source.token }を第2引数として渡してください。

class AxiosSample<{}, IState> extends React.Component {
    ...
    public componentDidMount() {
        axios
            .get(
                '/api/samples',
                { cancelToken: this.state.source.token }
            )
            .then(
                response => {
                    // 取得したデータを元に処理を行う。
                }
            )
            .catch(
                error => { alert(error) }
            )
    }
}

3. リクエストのキャンセル処理をcomponentWillUnmount()で行う

リスエストの処理中にページ遷移等でコンポーネントのアンマウントが実行されるとメモリ・リークを起こす可能性があります。防止策として、componentWillUnmount()でAxiosのキャンセル処理を行いましょう。

class AxiosSample<{}, IState> extends React.Component {
    ...
    public componentWillUnmount() {
        this.state.source.cancel('リクエストがキャンセルされました。')
    }
}

参照

8
8
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
8
8