When developing a React Native application with a persistent Redux store written in TypeScript, I encountered an issue:
I created a Thunk function that queries an API and receives question data in a fetch. The fetch operation works well, but when attempting to save data to the Redux Store using extraReducers
, errors occur.
This is how my code looks:
First, I dispatch the Thunk in my page:
questionpage.tsx
-stuff-
useEffect(() => {
console.log('dispatching fetch')
dispatch(fetchQuestions())
}, []);
-render stuff-
The actual Thunk function makes a fetch call to the API:
export const fetchQuestions = createAsyncThunk('questions/fetchquestions', async () =>{
let headers = new Headers();
headers.append('Authorization', 'Basic ' + Base64.btoa(email + ":" + password))
const response = await fetch(api + "/api/questions", {
headers: headers,
method: 'GET'
})
const stuff = await response.json();
console.log(stuff)
return stuff;
})
Then:
questionSlice
extraReducers: (builder) => {
builder.addCase(fetchQuestions.pending, (state, action) => {
state.status = 'loading' // < when I comment this the console.log works
console.log('pending')
}),
builder.addCase(fetchQuestions.fulfilled, (state, action) => {
state.status = 'succeeded'
// Add any fetched posts to the array
state.questions = state.questions.concat(action.payload) // < comment this, console.log works
console.log('fulfilled')
})
builder.addCase(fetchQuestions.rejected, (state, action) => {
state.status = 'failed' // < when I comment this the console.log works
state.error = action.error.message // < when I comment this the console.log works
console.log('rejected')
})
}
In the reducer, I use extraReducers
to handle the different outcomes of the Thunk function. However, I face an error when trying to update the state:
[Unhandled promise rejection: Error: [Immer] Immer only supports setting array indices and the 'length' property]
This error occurs even when modifying non-array variables like state.status
and also affects state.error
and state.questions
. The last one is an array, but the others are not.
I have tried troubleshooting based on Phry's comment about the state being treated as an array, but I couldn't find any indication of that in my code. It's a challenging situation for me, especially considering my level of experience.