Silver Library (Archived)
Note - To harmonise Redux & async data with axios 본문
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
'Face the fear, build the future > Revision Sector' 카테고리의 다른 글
[Redux Toolkit] How should I configure 'Store' (0) | 2022.12.31 |
---|---|
실용적일것 같은 JS Design Pattern (0) | 2022.12.30 |
Redux Toolkit 에 대해 알아보기. (0) | 2022.12.26 |
How to know 'Design Pattern' as the developer? (1) | 2022.12.16 |
react 에서 context 와, Provider 는 무슨 용도일까. (0) | 2022.12.15 |