[React] 코드비교

youngseo·2022년 8월 5일
0

REACT

목록 보기
37/52
post-thumbnail

코드비교

1. api 의 loading, data, error를 담는 Reducer작성

내코드

Reducer.js

const WeatherReducer = (state, action) => {
  switch (action.type) {
    case 'LOADING':
      return {
        ...state,
        loading: true,
      }
    case 'SUCCESS':
      return {
        ...state,
        data: action.data,
      }
    case 'ERROR':
      return {
        ...state,
        error: action.error,
      }
    default:
      throw new Error(`undefined actio type: ${action.type}`)
  }
}

export default WeatherReducer

Weatherprc.js

import React, { useEffect, useReducer } from 'react'
import axios from 'axios'
import WeatherReducer from '../reducer/weatherReducer'

function Weatherprc() {
  const [responseData, dispatchResponseData] = useReducer(WeatherReducer, {
    loading: false,
    error: false,
    data: null,
  })

  const queryParams = {
    serviceKey: process.env.REACT_APP_SERVICE_KEY,
    pageNo: 1,
    numOfRows: 100,
    dataType: 'JSON',
    base_date: '20220805',
    base_time: '0500',
    nx: 55,
    ny: 127,
  }

  const fetchData = async () => {
    try {
      dispatchResponseData({ type: 'LOADING', loading: true })
      const { data } = await axios.get(
        '/1360000/VilageFcstInfoService_2.0/getVilageFcst',
        { params: queryParams },
      )
      dispatchResponseData({
        type: 'SUCCESS',
        data: data['response']['body']['items']['item'],
      })
    } catch (error) {
      console.log(error)
      dispatchResponseData({ type: 'ERROR', error })
    }
    dispatchResponseData({ type: 'LOADING', loading: false })
  }

  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      {responseData.loading && !responseData.error && <p>Loading...</p>}
      {responseData.error && <p>에러가 발생했습니다</p>}
      {responseData.data &&
        !responseData.error &&
        responseData.data.map((data, index) => {
          return (
            <p key={index}>
              {data.category},{data.fcstDate},{data.fcstTime},
            </p>
          )
        })}
    </div>
  )
}

export default Weatherprc

모범 예시가 될 수 있는 코드

Reudcer

const WeatherReducer = (state, action) => {
  switch (action.type) {
    case 'LOADING':
      return {
        loading: true,
        data: null,
        error: null,
      }
    case 'SUCCESS':
      return {
        loading: false,
        data: action.data,
        error: null,
      }
    case 'ERROR':
      return {
        loading: false,
        data: null,
        error: action.error,
      }
    default:
      throw new Error(`undefined actio type: ${action.type}`)
  }
}

Weatherprc.js

import React, { useEffect, useReducer } from 'react'
import axios from 'axios'
import WeatherReducer from '../reducer/weatherReducer'

function Weatherprc() {
  const [responseData, dispatchResponseData] = useReducer(WeatherReducer, {
    loading: false,
    data: null,
    error: null,
  })

  const queryParams = {
    serviceKey: process.env.REACT_APP_SERVICE_KEY,
    pageNo: 1,
    numOfRows: 100,
    dataType: 'JSON',
    base_date: '20220805',
    base_time: '0500',
    nx: 55,
    ny: 127,
  }

  const fetchData = async () => {
    dispatchResponseData({ type: 'LOADING' })
    try {
      const { data } = await axios.get(
        '/1360000/VilageFcstInfoService_2.0/getVilageFcst',
        { params: queryParams },
      )
      dispatchResponseData({
        type: 'SUCCESS',
        data: data['response']['body']['items']['item'],
      })
    } catch (error) {
      dispatchResponseData({ type: 'ERROR', error })
    }
  }

  useEffect(() => {
    fetchData()
  }, [])

  if (responseData.loading) return <p>Loading...</p>
  if (responseData.error) return <p>{responseData.error}</p>
  return (
    <div>
      {responseData.data &&
        responseData.data.map((data, index) => {
          return (
            <p key={index}>
              {data.category},{data.fcstDate},{data.fcstTime},
            </p>
          )
        })}
    </div>
  )
}

export default Weatherprc

useContext와 useReducer를 이용한 코드

https://github.com/0seo8/weather_public_API

0개의 댓글