Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use patchState vs setState in NGXS?

I am learning ngxs but I can't understand when should I use patchState and setState? What's the difference?

const state = ctx.getState();
let data =  this.service.list();
ctx.setState({
    ...state,
    feedAnimals: data
});

vs.

let data =  this.service.list();
ctx.patchState({
    feedAnimals: data
});
like image 696
Александр Шатилов Avatar asked May 22 '18 08:05

Александр Шатилов


2 Answers

Those two pieces of code are equivalent. patchState is just a short hand version of the setState({...state, ... } code.

In future patchState will most likely be evolving to a more useful immutability helper with equality testing (ie. the state would only be changed if the patch actually changes any values) and patch operators (this is still in discussion).

I would recommend using patchState for neatness and to take advantage of features that are on their way.

like image 55
Mark Whitfeld Avatar answered Sep 23 '22 00:09

Mark Whitfeld


IT DOESN'T WORK PROPERLY

const state = context.getState();
state.permissions = action.payload;
context.setState(state);

IT WORKS

const state = context.getState();
state.permissions = action.payload;
context.setState({ ...state });

IT WORKS

const state = context.getState();
state.permissions = action.payload;
context.patchState(state);

All the examples update the state... but the first one doesn't activate the observable for state changes, because state is immutable, that means you cannot simple edit it and save it, it is not editable and you always will have to clone the old state, edit your new copy and save this new state. patchState just does it for you.

like image 41
Michalis Avatar answered Sep 27 '22 00:09

Michalis