Reputation: 1759
How can I assign an entire array to my intialState object using RTK?
Doing state = payload
or state = [...state, ...payload]
doesn't update anything.
Example:
const slice = createSlice({
name: 'usersLikedPosts',
initialState: [],
reducers: {
getUsersLikedPosts: (state, { payload }) => {
if (payload.length > 0) {
state = payload
}
},
},
})
payload looks like this:
[
0: {
uid: '1',
title: 'testpost'
}
]
update
Doing this works but I don't know if this is a correct approach. Can anyone comment?
payload.forEach((item) => state.push(item))
Upvotes: 10
Views: 12984
Reputation: 44086
immer
can only observe modifications to the object that was initially passed into your function through the state
argument. It is not possible to observe from outside the function if that variable was reassigned, as it only exists in the scope within the function.
You can, however, just return
a new value instead of modifying the old one, if you like that better. (And in this case, it is probably a bit more performant than doing a bunch of .push
calls)
So
return [...state, ...payload]
should do what you want.
Upvotes: 15