Redux-thunk

Goofi·2023년 2월 6일
0

❗️생활코딩 redux toolkit - thunk 강의를 듣고 정리한 게시물입니다.

Redux-thunk

Redux-toolkit에는 기본적을 thunk가 내장 되어 있다.

createAsyncThunk는 비동기 작업을 처리하는 액션을 만들어 준다.**

<button onClick={()=>{
	dispatch(asyncUpFetch());
}}>+ async thunk</button>
<div>{count} | {status}</div>


const asyncUpFetch = createAsyncThunk( //asyncUpFetch는 액션 크리에이터이기 때문에 타입을 적어 주었다.
	'countSlice/asyncUpFetch', //Type을 적어 준 것이다.
  async ()=>{
  	const resp = await fetch('https://~~~') 
    const data = await resp.json();
    return data.value;
  }
)

const counterSlice = createSlice({
	name : 'counterSlice',
	initialState : {
    	value : 0,
      	status : 'Welcome'
    },
  	reducers : {
    	up : (state, action)=>{
       		state.value = state.value + action.payload;
        }
    }
	extraReducers : (builder) =>{
    	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';
        })
    }
})

📌동기적인 action → reducers 사용
📌비동기적인 action → extraReducers 사용

둘이 차이점이 무엇인가?
reducres(동기)를 사용하게 되면 액션 크리에이터를 자동으로 만들어 준다. 툴킷은 extraReducers(비동기) 액션 크리에이터를 자동으로 못 만들어준다.
그래서 비동기는 extraReducers 안에서 정의를 한다.

profile
안녕하세요! 👋 개발과 운영을 공부하고 있습니다. 코드를 작성하는 것만큼 서비스가 안정적으로 운영되는 것에도 관심이 많습니다. 프론트엔드부터 백엔드, 그리고 인프라 운영까지 전체적인 서비스 생명주기를 이해하면서 공부하고 있습니다.

0개의 댓글