Skip to content

커스텀 훅 #2

@ijieun0123

Description

@ijieun0123

🔗   참고 링크

간단한 리액트 커스텀 훅 만들어보기
React Hooks CRUD example with Axios and Web API
useAxios : A simple custom hook for calling APIs using axios ( 적용 실패 )



📝   메모

* 커스텀 훅은 core 디렉토리 안에 정리함
* 커스텀 훅 이름은 'use + 마음대로 명칭 정하기'  이렇게 지으면 된다.
* useNavi.js ( 네비게이션 ), usePage.js ( 페이지네이션 ), axios 에 적용해 봄
* 커스텀 훅은 중복되는 훅들을 다 저장해두었다가 언제든 꺼내쓸 수 있는 개념으로 이해함


🔵   usePaging 예시

  1. usePage.js 커스텀 훅 생성
const usePage = value => {
  const [page, setPage] = useState(1)
  const onChangePage = (e, newPage) => setPage(newPage)

  useEffect(() => {
    setPage(1)
  }, [value ? value : null])

  return {page, onChangePage}
}

  1. 커스텀 훅 꺼내쓰기
import usePage from '../core/usePage'

const {page, onChangePage} = usePage(value)


🔵   axios 예시

  1. axios>http-common.js baseURL 을 담는다.
import axios from 'axios'

export default axios.create({
  baseURL: 'https://api.themoviedb.org/3/movie',
  headers: {
    'Content-type': 'application/json',
  },
})

  1. axios>api.js baseURL + 나머지 주소 를 붙여 여러가지 api 들을 담아둠.
const getMovies = (keyword, page) => {
  return http.get(
    `/${keyword}?api_key=${process.env.REACT_APP_MOVIE_API}&language=en-US&page=${page}`
  )
}

const getDetail = id => {
  return http.get(
    `/${id}?api_key=${process.env.REACT_APP_MOVIE_API}&language=en-US`
  )
}

const api = {
  getMovies,
  getDetail,
}

export default api

  1. api 가 필요할 때 다음과 같이 꺼내쓰면 된다.
import api from '../axios/api'

const getMovies = () => {
    const keyword = valueArr[value]
    api
      .getMovies(keyword, page)
      .then(res => {
        console.log(res.data)
        const {results, total_pages} = res.data
        setCount(total_pages)
        dispatch(MOVIES(results))
      })
      .catch(e => {
        console.log(e)
      })
}


✅   체크리스트

  • axios 훅은 현재 results 를 사용하는 방식이 비슷하므로 가능하면 중복코드를 없애기

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions