const asyncUpFetch = createAsyncThunk(
'counterSlice/asyncUpFetch', //type
async () => {
const resp = await fetch('https://~~~') //요청 : 서버접속
const data = await resp.json(); // 결과를 가져오고
return data.value; // 그 결과를 return반환한다 -> 두번째 매개변수의 함수로 전달했다
createAsyncThunk는 비동기 작업을 처리하는 action을 만들어준다.
비동기 작업은 크게 3가지의 상태를 가진다
1. asyncUpFetch.pending : 비동기 작업을 시작했을때 상태
2. asyncUpFetch.fulfilled : 비동기 작업이 끝났을때 (데이터를 가져왔을때)
3. asyncUpFetch.rejected : 오류가 생겨 중단되었을때
: 3가지 상태별로 reducer가 필요하다 (fulfilled만 정의해도 상관없다.)
그 reduxer는 createSlice에서 extraReducers에 builder.addCase를 통하여 상태에 따른 리듀서를 두번째 파라미터이 함수로 제공
ex)
const counterSlice = createSlice({
name: 'counterSlicer',
initalState: {
value: 0,
status: 'Welcome'
},
reducers: { // 동기적인 action
up: (state, action) => {
state.value = state.value + action.payload;
}
},
: reducers 동기적인 action
actionCreate를 리덕스 툳킷이 자동으로 만들어준다
extraReducers: (builder) => { // 비동기적인 action
builder.addCase(asyncUpFetch.pending, (state, action) => {
state.status = 'Loading';
})
builder.addCase(asyncUpFetch.fulfilled, (state, action) => {
state.value = action.payload;
state.status = 'complete';
})
builder.addCase(asyncUpFetch.rejected, (state, action) => {
state.status = 'fail';
})
}
});
: 비동기 작업은 actionCreate를 자동으로 만들어주지 않는다
그런 것들은 extraReducer를 통하여 처리한다
상태에 따른 리듀서의 status가 useSeletor를 통하여 컴포넌트에 출력할 수 있다
그때 data.value에 전달된 데이터가 fulfilled의 action.payload라는 약속된 이름으로써 주입됨 -> 그것을 state.value로 담아준다
value값을 useSelector가 받으면 그것을 counter란 이름으로 서버로부터 가져온 counter 정보가 출력됨