일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- React
- map()에는 key값이 필요
- 오공완
- 리액트
- 리스트랜더링
- 오공완 #리액트 공부 #React
- 클래스 추가하기 #특정 url 클래스 추가 #사이트 접속시 클래스 추가 #오공완 #javascript
- Today
- Total
new_bird-hyun
Redux Toolkit의 Thunk를 사용한 비동기 상태 관리 본문
//store.js
import { configureStore, createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
return response.json();
});
const postsSlice = createSlice({
name: 'posts',
initialState: { posts: [], status: 'idle', error: null },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchPosts.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchPosts.fulfilled, (state, action) => {
state.status = 'succeeded';
state.posts = action.payload;
})
.addCase(fetchPosts.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
});
},
});
const store = configureStore({
reducer: {
posts: postsSlice.reducer,
},
});
export default store;
// App.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPosts } from './store';
import { Provider } from 'react-redux';
import store from './store';
function Posts() {
const dispatch = useDispatch();
const { posts, status, error } = useSelector((state) => state.posts);
useEffect(() => {
if (status === 'idle') {
dispatch(fetchPosts());
}
}, [status, dispatch]);
if (status === 'loading') return <p>Loading...</p>;
if (status === 'failed') return <p>Error: {error}</p>;
return (
<div>
<h1>Posts</h1>
<ul>
{posts.slice(0, 10).map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Posts />
</Provider>
);
}
export default App;
// Redux Toolkit의 Thunk를 활용하면 비동기 상태 관리가 간소화됨
'코딩 공부' 카테고리의 다른 글
Redux Toolkit Query로 Mutation 구현하기 (1) | 2024.12.27 |
---|---|
Redux Toolkit Query를 활용한 데이터 패칭 (1) | 2024.12.26 |
React와 Redux Toolkit으로 상태 관리하기 (0) | 2024.12.23 |
React에서 Custom Hook으로 코드 재사용성 높이기 (0) | 2024.12.22 |
React에서 Error Boundary로 에러 처리하기 (1) | 2024.12.20 |