0

How i make an array in the new reducer?

With old syntax id do this:

    const initialState: Comment = {
      fullName: null,
      comment: null
    };

    export function commentReducer(state: Comment[] = [], action: CommentAction.Action) {
      switch (action.type) {
        case CommentAction.ADD_COMMENT:
          return [...state, action.payload];
        case CommentAction.REMOVE_COMMENT:
          state.splice(action.payload, 1);
          return state;
          default:
            return state;
      }

    }

Now in new reducer i do this but its not array

    export const initialState: Comment = {
      fullName: null,
      comment: 'null'
    };

    const commentReducer = createReducer(
      initialState,
      on(CommentAction.addcomment, (state, { fullName, comment }) => ({ fullName, comment }))
    );


    export function reducer(state: Comment | undefined, action: Action) {
      return commentReducer(state, action);
    }

I try to dispatch but its not add to array it just replace it. What i do wrong?

1 Answer 1

1

firstly: your initialState should be an array, secodly: just return an array

export const initialStat: Comment[] = [];

const commentReducer = createReducer(
      initialState,
      on(CommentAction.addcomment, (state, { fullName, comment }) => [...state, { fullName, comment }])
    );

  export function reducer(state: Comment[], action: Action) {
      return commentReducer(state, action);
    }

I also fixed types Comment to Comment[] where it was required

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.