-2

Trying to understand a code snippet. What does ...this.savedSettings() do in the following snippet. afaik, ellipsis is used for destructuring and to pass variables to a function (spread syntax)

    constructor(props) {
        super(props);
        this.state = {
            page: 'dashboard',
            ...this.savedSettings(),  // THIS LINE
            setPage: this.setPage,
        };
    }

    savedSettings() {
        if(noData) {
            return {page: 'settings', firstVisit: true};            
        }
        return {};
    }

PS: I understand that there is a similar question here as mentioned by mod. I did refer to the same before putting this one out. Goes without saying, the spread syntax is subtle and that question was a generic, albeit well answered, question on applying it on an object like props in a React component. It was not immediately clear to me how to apply that here.

This question is more generic as to applying spread syntax against a JS function call. IMHO for someone not very experienced/on the way of being experienced, the subtle difference can be confusing and a question/snippet like this can be profitable.

That said, I've answered this myself. While SE runs promos to ask questions, they should highlight the fact that it risks reputation. Thanks for the downvotes.

hyperbolicme
  • 29
  • 1
  • 8

1 Answers1

0

This is in fact used as spread syntax. The syntax is applied to the returned object. It merges the given object (this.state with the object returned by the function this.savedSettings(). Resulting in this.state being assigned with

// if noData is true
        {
            page: 'settings',  // MERGED/OVERWRITTEN 
            firstVisit: true,  // MERGED/ADDED
            setPage: this.setPage,
        };

or

// if noData is false
        {
            page: 'dashboard',  
            setPage: this.setPage,
        };
hyperbolicme
  • 29
  • 1
  • 8