반응형
중복된 ID를 확인하기 위해서 MovieItem.vue 코드를 수정한다.
<template>
<div>
{{ movie.imdbID }}
</div>
</template>
<script>
export default {
props: {
movie: {
type: Object,
default: () => ({})
}
}
}
</script>
브라우저 확인 (중복된 데이터를 확인할 수 있다.)
프론트쪽에서 중복된 데이터를 제거하기 위해서 lodash api에 uniqBy 메소드를 이용한다.
공식 문서: https://lodash.com/docs/4.17.15#uniqBy
Lodash Documentation
_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti
lodash.com
lodash api 설치
명령어: npm i lodash
lodash 사용
movie.js 수정
import axios from 'axios'
// 중복제거을 위해서 uniqBy를 사용
import _uniqBy from 'lodash/uniqBy'
export default {
// module!
namespaced: true,
//data!
state: () => ({
movies: [],
message: '',
loading: false
}),
// computed!
getters: {
// 실제 데이터를 계산해서 새로운 데이터 형식으로 반영할때 사용
},
// methods!
// 변이: 관리하는 데이터를 변경시켜줄수 있다. 다른 메소드에서 변경할 수 없다.
mutations: {
// ['movies', 'message', 'loading']
updateState(state, payload) {
Object.keys(payload).forEach(key => {
state[key] = payload[key]
})
},
// assignMovies (state, Search){
// state.movies = Search
// },
resetMovies(state) {
state.movies = []
}
},
// 비동기로 동작한다.
actions: {
async searchMovies({state, commit}, payload) {
const { title, type, number, year } = payload
const OMDB_API_KEY = '7035c60c'
// http -> https 로 변경
const res = await axios.get(`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=1`);
// console.log(res);
const { Search, totalResults } = res.data
commit('updateState', {
// 검색된 imdbID 데이터의 중복을 제거
movies: _uniqBy(Search,'imdbID')
// message: 'Hello world',
// loading: true
})
console.log(totalResults) // 261
console.log(typeof totalResults) // string
const total = parseInt(totalResults, 10)
const pageLength = Math.ceil(total / 10)
// 추가 요청!
if (pageLength > 1) {
for (let page = 2; page <= pageLength; page += 1) {
if (page > number / 10) {
// 반복문 종료
// 사용자가 지정한 갯수만큼 보여주도록 설정
break;
}
const res = await axios.get(`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`);
const {Search} = res.data
commit('updateState', {
// _uniqBy 를 이용해서 중복 제거
movies: [
...state.movies,
..._uniqBy(Search, 'imdbID')
]
})
}
}
}
}
}
브라우저 확인(중복제거 확인)
반응형
'프론트엔드 > Vue.js' 카테고리의 다른 글
비동기 예외 처리(then, catch, finally) (0) | 2021.09.10 |
---|---|
비동기 - 콜백(callback)과 프로미스 객체 (0) | 2021.09.09 |
Search - 버튼 구현하기 (0) | 2021.08.31 |
Search - 필터 구현하기 (0) | 2021.08.30 |
헤드라인 만들기 (0) | 2021.08.17 |