Reputation: 666
I try to update my state when adding an item in array, using react/redux and redux-saga middleware. But where I do this, I have an array, where each item have an index (0, 1, 2....) but when I add the new item (named step), the new item doesn't have an index but it is like :
[
0: item1,
1: item2,
2: item3,
step: newItem
]
And I want that the new item have an index like 3: newItem
Here is the reducer :
export function stepReducer(state = [], action) {
switch (action.type) {
case Actions.CREATE_STEP_REQUEST:
return state;
case Actions.STEP_CREATED:
let newArray = action.steps.slice();
newArray.splice(action.index, 0, action.step);
return newArray;
case Actions.FETCH_TRAVEL_STEPS_REQUIRED:
return state;
case Actions.TRAVEL_STEPS_DATA_SUCCESS:
let updatedSteps = _.merge(action.steps, state.steps);
return updatedSteps;
default:
return state;
}
}
and the saga file :
export function* createStep(action) {
const step = yield call(stepApi.createStep, action.travelId, action.step, action.authToken);
const steps = yield select((state) => state.steps);
const index = steps.length;
yield put({ type: Actions.STEP_CREATED, steps, step, index });
}
if someone should help,
thank !
Upvotes: 2
Views: 2347
Reputation: 31024
It seems that you are working with lodash
, note that _.merge
works with objects not arrays.
If you just want to add a new item to the END of an array you can use the ES2015 spread feature:
const nextState = [...state, action.step];
Upvotes: 2