관리 메뉴

Silver Library (Archived)

Note - To harmonise Redux & async data with axios 본문

Face the fear, build the future/Revision Sector

Note - To harmonise Redux & async data with axios

Ayin Kim 2022. 12. 31. 12:18
반응형

이 부분을 두고 '어떻게 할까...' 하던 중, 그냥 async 로 할 때 Redux 를 쓰게 될 경우에는

'redux -> axios' 로 조합을 구성 하면 되겠다는 잠정 결론이 나왔습니다.

 

이 글은 redux-thunk middleware 개념을 적용해서 async data 과정에서 axios를 함께 적용하는 사례를 기반으로 간략히 기록되었습니다.

 

Prerequisite.

- You need to install the following:

npm i axios redux-thunk

 

Redux Thunk. Thunk middleware for Redux. It allows writing functions with logic inside that can interact with a Redux store's dispatch and getState methods.

 

GitHub - reduxjs/redux-thunk: Thunk middleware for Redux

Thunk middleware for Redux. Contribute to reduxjs/redux-thunk development by creating an account on GitHub.

github.com

const redux = require('redux')
const thunkMiddleware = require('redux-thunk').default
const axios = require('axios')
const createStore = redux.createStore
const applyMiddleware = redux.applyMiddleware

const initialState = {
	loading: false,
    users [],
    error: '',
}

const FETCH_USERS_REQUESTED = 'FETCH_USERS_REQUESTED'

const fetchUsersRequest = () => {
	return {
    	type: FETCH_USERS_REQUESTED,
    }
}

...

const fetchUsers = () => {
	return function(dispatch) {
    	dispatch(fetchUsersRequest())
		axios
        .get('https://URL(ex.jsonplaceholder)')
        .then(response => {
        	// response.data indicates 'users'
    		const users = response.data.map(user => user.id)    
            dispatch(fetchUsersSuccess(users))
    	})
        .catch(error => {
        	// error.message indicates error message
        	dispatch(fetchUsersFailure(error.message))
    	})
	}
}

const store = createStore(reducer, applyMiddleware(thunkMiddleware))

store.subscribe(() => { console.log(store.getState())})
store.dispatch(fetchUsers())

Pros.

- You can also use Redux base approach to async data.

- Used in the industry.

 

Cons.

- Not sure whether this is ultimate way to reduce the code line.

 

Note.

Using with 'Immer' might be helpful.

 

React Redux middlewares: Thunk vs Saga

Today we’re going to discuss Redux middlewares for async tasks. But before going through it, we should first understand why do we need…

blog.devgenius.io