This project was bootstrapped with Create React App, using the Redux and Redux Toolkit TS template.
-
install
# Redux + Plain JS template npx create-react-app my-app --template redux # Redux + TypeScript template npx create-react-app my-app --template redux-typescript
npm install @reduxjs/toolkit
-
RTK là một thư viện giúp mình viết Redux tốt hơn, dễ hơn và đơn giản hơn.
-
Ba vấn đề làm nền tảng ra đời RTK:
- Configuring a Redux store is too complicated. - I have to add a lot of packages to get Redux to do anything useful. - Redux requires too much boilerplate code.
- Wrap `createStore` để cung cấp những tùy chọn cấu hình và mặc định đơn giản.
- Nó có thể tự động kết hợp với `slice reducers`, thêm bất kỳ Redux middleware mà bạn cung cấp, bao gồm `redux-thunk` (mặc định)
- Nó cũng cho phép sử dụng Redux DevTools Extension.
- Chấp nhận một đối tượng các hàm reducers, một slice name, một initial state value.
- Nó tự động tạo một `slice reducer` với các action creators và action types tương ứng.
- Một hàm nhận đối số là một Redux action type string và một hàm callback mà sẽ trả về một promise.
- Nó tạo promise lifecycle action types dựa trên action type prefix mà bạn đã chyền vào
- Trả về một thunk action creator mà sẽ chạy promise callback và dispatch the lifecycle actions dựa trên the returned promise.
export const getTodos = createAsyncThunk('todos/todosFetched', async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
return response.data;
})
- This abstracts the standard recommended approach for handling async request lifecycles.
- It does not generate any reducer functions, since it does not know what data you're fetching, how you want to track loading state, or how the data you return needs to be processed. You should write your own reducer logic that handles these actions, with whatever loading state and processing logic is appropriate for your own app.