Created
July 25, 2023 05:46
-
-
Save godjooyoung/1bdcca6c2a2c006cd20226282bfb8101 to your computer and use it in GitHub Desktop.
전역 스토어를 통해 사용자 주소를 저장할때 미들웨어를 사용해서 외부 api 요청을 구현하여 반복되는 코드 사용을 줄였습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSlice } from '@reduxjs/toolkit' | |
import { getAddress } from '../../axios/api/kakao' | |
// 초기상태 설정 (사용자 위치 정보가 없을 경우 지도에 보여줄 기본 위치) | |
const initialState = { | |
userLatitude: 37.5561332, | |
userLongitude: 126.8656449, | |
userTown: '서울특별시 강서구 염창동', | |
} | |
const userSlice = createSlice({ | |
name: 'userInfo', | |
initialState: initialState, | |
reducers: { | |
__userLocation: (state, action) => { | |
const { latitude, longitude } = action.payload; | |
state.userLatitude = latitude; | |
state.userLongitude = longitude; | |
}, | |
__userTown: (state, action) => { | |
state.userTown = action.payload; | |
}, | |
__logoutResetUser: (state, action) => { | |
state = initialState | |
}, | |
} | |
}) | |
export const fetchUserLocation = (userLocation) => async (dispatch) => { | |
try { | |
// 좌표 to 주소 GET 요청 | |
const response = await getAddress({ | |
x: userLocation.longitude, | |
y: userLocation.latitude, | |
}); | |
// 액션 디스패치 | |
dispatch(__userLocation({ latitude: userLocation.latitude, longitude: userLocation.longitude })); | |
dispatch(__userTown(response.documents[0].address_name)); | |
} catch (error) { | |
// 에러 처리 | |
// console.log('카카오 요청 에러:', error); | |
} | |
}; | |
export const { __userLocation, __userTown, __logoutResetUser} = userSlice.actions | |
export default userSlice.reducer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment