Search code examples
javascriptreactjsreactjs-fluxalt.js

Is setState() optional for updating the state in Alt.js store?


Yeah, I know that setState() updates a Store's state and emit a change event to all subscribers, but I find out that not everyone uses it and omit it when they update the state.

For example in the following alt-todo repo, they don't use setState():

class TodoStore {
    constructor() {
        this.bindActions(TodoActions);

        this.todos = {};
    }

    onCreate(text) {
        text = text.trim()
        if (text === '') {
            return false
        }
        // hand waving of course.
        const id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36)
        this.todos[id] = {
            id: id,
            complete: false,
            text: text
        }
    }
}

However in the official alt.js repo they use it:

class LocationStore {
    constructor() {
        this.bindAction(locationActions.updateLocation, this.onUpdateLocation);

      this.state = {
        city: 'Denver',
        country: 'US'
      };
    }

    onUpdateLocation(obj) {
        const { city, country } = obj
        this.setState({ city, country });
    }
}

So I'm wondering what's the difference in the both ways?


Solution

  • There isn't one, really:

    setState is used internally by Alt to set the state. You can override this to provide your own setState implementation. Internally, setState is an alias for Object.assign. setState must return an object.

    http://alt.js.org/docs/createStore/#setstate

    An example: Let's say your state is:

    {
      city: 'Denver',
      country: 'US',
    }
    

    The two ways of updating state:

    this.setState({city: 'Colorado Springs'})
    console.log(this.state) // {city: 'Colorado Springs', country: 'US' })
    
    this.state = { city: 'Elbert' }
    console.log(this.state) // state is {city: 'Elbert'}
    

    As you can see, this.state = overwrites the state, while this.setState() merges the new state into the old. See Object.assign()