I understand this has been asked before but so far no answers except someone making a syntax mistake. I have verified this against every tutorial I’ve seen online and I can’t find the issue. It seems to be coming from the fullfilled extraReducer
JavaScript
x
65
65
1
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
2
import axios from "axios";
3
4
const KEY = process.env.REACT_APP_API_KEY
5
const BASE_URL = process.env.REACT_APP_BASE_URL
6
const GLOBALVIEWS_API = `${BASE_URL}/countrymap`
7
8
const initialState = {
9
mapdata:{},
10
status: 'idle', //'idle', 'loading', 'succeeded', 'failed'
11
error:null
12
}
13
14
export const fetchMapData = createAsyncThunk(
15
'mapdata/fetchMapData',
16
async (id) => {
17
const response = await axios.get(
18
GLOBALVIEWS_API,
19
{
20
headers: {
21
'Content-Type': 'application/json',
22
'X-API-KEY': KEY,
23
},
24
params: {
25
titleId: id,
26
}
27
}
28
)
29
30
return response.data.Item;
31
}
32
)
33
34
const mapSlice = createSlice({
35
name: 'mapdata',
36
initialState,
37
reducers:{
38
addMapData: (state, { payload }) => {
39
state.mapdata = payload
40
}
41
},
42
extraReducers: {
43
[fetchMapData.pending]: () => {
44
console.log("Pending");
45
},
46
[fetchMapData.fulfilled]: (state, { payload }) => {
47
state.status = 'succeeded'
48
console.log("Succeeded", payload);
49
return {state, mapdata: payload}
50
},
51
[fetchMapData.rejected]: () => {
52
console.log("Rejected");
53
},
54
}
55
})
56
57
// SELECTORS
58
export const getMapStatus = (state) => state.mapdata.status;
59
60
export const allMapData = (state) => state.mapdata.mapdata;
61
export const { addMapData } = mapSlice.actions;
62
63
64
export default mapSlice.reducer
65
In the component, nothing weird, and yes everything is imported
JavaScript
1
16
16
1
const {id} = useParams();
2
const dispatch = useDispatch();
3
4
const allmapdata = useSelector(allMapData)
5
const addmapdata = useSelector(addMapData)
6
const mapStatus = useSelector(getMapStatus)
7
8
useEffect(() => {
9
dispatch(fetchMapData(id))
10
11
lazy(setMap(allmapdata))
12
console.clear()
13
console.log("mapdata: ", allmapdata);
14
15
}, [id, allmapdata, dispatch])
16
You can see in my image below that my fetch is successful and I am getting data. So how do I get rid of this error? Thanks in advance.
Advertisement
Answer
This is the issue:
JavaScript
1
4
1
state.status = 'succeeded'
2
console.log("Succeeded", payload);
3
return {state, mapdata: payload}
4
That is indeed both a “mutation of the existing state
” and a “return of a new value”, and that’s exactly what the error is warning you about.
You can change that to:
JavaScript
1
3
1
state.status = 'succeeded'
2
state.mapdata = action.payload
3