David
David

Reputation: 492

How to properly push and receive data from ngrx store

I'm trying to works with ngrx store and faced with problem, to properly push data in my store and select it.

My store object look like

AppStore = {
  chat: {
    messages: []
  }
}

and my reducers looks like

const initialState = {
  messages: []
};

export const ChatReduce = (state = initialState, action:Action) => {
  if (typeof state === 'undefined') {
    return initialState;
  }
  switch(action.type){
    case 'ADD_MESSAGE':
      return {
        ...state,
        messages: [...state.messages, action.payload]
      };
    default:
      return state;
  }
};

in case "ADD_MESSSAGE" I want to push new message object from action payload and return new state. what am I doing wrong? Right now my state's chat message array just rewrites one value every time I push new message, but old messages are not saves.

And after write to store, how to select messages of me state? Is it necessary to subscribe to data? I tried this.store.select('chat') but how to get messages?

Upvotes: 1

Views: 1716

Answers (2)

Phaseka Malatji
Phaseka Malatji

Reputation: 11

Heres how i approached it,

  ngOnInit() {
  this.getStudents();
  this.students$ = this.store.select(state => state.students)
  this.students$.forEach( v => console.log(v))
  }

  getStudents(){
  // we want to dispatch na action 
  this.store.dispatch(new studentActions.LoadStudentsAction())
}

Upvotes: 1

seescode
seescode

Reputation: 2131

I was able to get it to add without overriding:

https://jsfiddle.net/seesyong/stL5o0ck/

If you want to pull out just the messages you could do:

this.store.select(state => state.chat)
  .subscribe(chat => {
  console.log(chat.messages);
});

Upvotes: 0

Related Questions