Reputation: 3434
I'm using ReactNative + React Redux.
My Reducer:
const initialState = {
categories: []
}
case "FETCHING_SUCCESS":
return {
...state,
isAdding: false,
categories: [...state.categories, action.data]
}
The data that I receive is :
[
{id:1, name: 'name01', someId: 11},
{id:2, name: 'name02', someId: 22},
{id:3, name: 'name03', someId: 33}
]
If I do:
case "FETCHING_SUCCESS":
return {
...state,
isAdding: false,
categories: action.data // <= Notice This
}
I get the data fine - console.log("CATEGORIES: ", this.props.caregories); :
But I want to append the received data to the existing data. So if I do:
categories: [...state.categories, action.data]
I get an Array into an array :
And on further API calls, multiple arrays nested into the primary one.
How do I solve this? I just want the primary array and not arrays nested in the primary array. I can map
and show the data from the primary array. I don't understand how else I'm supposed to append the data.
Many thanks.
Upvotes: 1
Views: 28
Reputation: 243
Your codde should be:
case "FETCHING_SUCCESS":
let newCategories = [...state.categories, ...action.data];
return {
...state,
isAdding: false,
categories: newCategories
}
Check this snippet out :)
var state = {
categories: [1,2,3,4],
isAdding: true,
done: false
};
let data = [5,6,7,8];
let newcategories = [...state.categories, ...data];
state = {
...state,
isAdding: false,
categories: newcategories // <= Notice This
}
console.log(state)
Upvotes: 1
Reputation: 5293
I think what you meant to do is categories: [...state.categories, ...action.data]
.
Upvotes: 1