LoginSignup
0
0

More than 3 years have passed since last update.

Reactでaxiousを使って詳細ページを作る

Posted at

今回はaxiousを使ってタスク詳細ページを作る

APIを記述

src/service/v1ApRequest.js
import axios from 'axios'

// Taskの詳細ページのAPI
export const getTaskSubscriptionDetail = (id = ":id") => axios.get(`${API_ROOT}/task_subscriptions/${id}`)

:point_up_tone1:APIのリクエストがたくさんあるときは一つのファイルにまとめておくとわかりやすい

タスク詳細ページ作成

src/containers/TaskDetailPage.js
import { getTaskSubscriptionDetail } from '../services/v1ApiRequest'
import { SET_TASKSUBSCRIPTION } from '../constants/actionTypes'
import TaskSubscription from '../models/taskSubscription'

class TaskDetail extends Component {
  componentDidMount() {
    // this.props.match.params.idは
    // ..../path/to/:id の :idの部分をとってくれる
    // ..../path/to/:hoge_id だったら
    // this.props.match.params.hoge_id で取得できる
    // mapDispatchToPropsで定義したAPIを呼び出してStoreに保存するための関数を実行
    this.props.fetchTaskDetail(this.props.match.params.id);
  }

  render() {
    return (
          <div className={styles.taskName}>{this.props.taskSubscription.task.name}</div>
    )
  }
}
const mapStateToProps = ({ app, taskSubscription }) => ({
  isLoading: app.isLoading,
  taskSubscription: taskSubscription.selected // 4. APIのレスポンスがここに入る
})

//APIの結果をactionとしてdispatchする→コンポーネント側でやるならmapDispatchPropsを使う
const mapDispatchToProps = dispatch => ({
  fetchTaskDetail: (id) => {
    // 1. API呼び出して
    getTaskSubscriptionDetail(id)
      .then((res) => {
        // 2. レスポンスを受け取って
        console.log(res.data);
        // 3. dispatchにレスポンスを変換したもの(API)をpayloadにセットしたアクションをReducerへ運ばせる
        dispatch({
          type: SET_TASKSUBSCRIPTION,
      //payload: res.data だとスネークケースになるので、以下でキャメルケースにする
          payload: TaskSubscription.newFromApiResponse(res.data)
        })
      })
      .catch((error) => {
        // API読んでる最中にエラーが発生したらこっちが実行される
        console.log(error);
      });
  }
})
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(TaskDetail))


ルーティング

src/routes/index.js
 tasks: (id) => `/tasks${id ? `/${id}` : "" }`, 
// idがないときは一覧(/tasks)、idがあるときは詳細(/tasks/:is)のページへ
0
0
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
0
0