I try to remove one index in array with NgRx v8 and the action dispatch but its remove all the array except the first item in the array.
I try to remove 1 item from my array and its not work.
Reducer:
import { Comment } from '../models/comment.model';
import * as CommentAction from '../actions/comment.actions';
import { Action, createReducer, on } from '@ngrx/store';
export const initialState: Comment[] = [];
const commentReducer = createReducer(
initialState,
on(CommentAction.addcomment, (state, { fullName, comment }) => [...state, { fullName, comment }]),
on(CommentAction.removecomment, (state, { index }) => state.splice(index, 1))
);
export function reducer(state: Comment[], action: Action) {
return commentReducer(state, action);
}
action
import { createAction, props } from '@ngrx/store';
import { Comment } from '../models/comment.model';
export const addcomment = createAction(
'[COMMENT] Add',
props<Comment>()
);
export const removecomment = createAction(
'[COMMENT] Remove',
props<{ index: number }>()
);
components:
delComment(i) {
this.store.dispatch(removecomment({index: i}));
}
html:
<div class="right" *ngIf="comment$">
<h3>Comment</h3>
<!-- <ul> -->
<li (click)="delComment(i)" *ngFor="let comm of comment$ | async; let i = index">
<p> Name: {{comm.fullName}}</p>
<p> Comment: {{comm.comment}}</p>
<!-- </li>
</ul> -->
</div>
it's because splice
doesn't return array without the removed item, instead of this it returns the array consists of removed items :)
to make it work you should do sth like this:
on(CommentAction.removecomment, (state, { index }) => {
const array = [...state];
array.splice(index, 1);
return array;
})