Debug This Redux Code
You're using Redux Toolkit to fetch posts. The code below doesn't work as expected — the state doesn't update and errors aren't shown properly.
1import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
2import axios from 'axios';
3
4export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
5 const res = axios.get('https://jsonplaceholder.typicode.com/posts');
6 return res.data;
7});
8
9const postsSlice = createSlice({
10 name: 'posts',
11 initialState: {
12 items: [],
13 status: 'idle',
14 error: null
15 },
16 reducers: {},
17 extraReducers: builder => {
18 builder
19 .addCase(fetchPosts.pending, state => {
20 state.status = 'loading';
21 })
22 .addCase(fetchPosts.fulfilled, (state, action) => {
23 state.status = 'succeeded';
24 state.items = action.payload;
25 })
26 .addCase(fetchPosts.rejected, (state, action) => {
27 state.status = 'failed';
28 state.error = action.error;
29 });
30 }
31});
32
33export default postsSlice.reducer;
34
1import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
2import axios from 'axios';
3
4export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
5 const res = axios.get('https://jsonplaceholder.typicode.com/posts');
6 return res.data;
7});
8
9const postsSlice = createSlice({
10 name: 'posts',
11 initialState: {
12 items: [],
13 status: 'idle',
14 error: null
15 },
16 reducers: {},
17 extraReducers: builder => {
18 builder
19 .addCase(fetchPosts.pending, state => {
20 state.status = 'loading';
21 })
22 .addCase(fetchPosts.fulfilled, (state, action) => {
23 state.status = 'succeeded';
24 state.items = action.payload;
25 })
26 .addCase(fetchPosts.rejected, (state, action) => {
27 state.status = 'failed';
28 state.error = action.error;
29 });
30 }
31});
32
33export default postsSlice.reducer;
34
Let me know if you want the fixed version too!