Valentin Rochet
Valentin Rochet

Reputation: 157

React: Spread the return of a function in one line

Is it possible to spread the result of a function directly, instead of storing then spreading it? In other words, is there a way to reduce these 2 lines into one?

const toto = removePreviousCase();
setMap({
    ...toto,
    player: {
        y: selectedCase.y,
        x: selectedCase.x
    }
});

Upvotes: 3

Views: 187

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

Just spread the removePreviousCase call into the object that setMap gets called with:

setMap({
    ...removePreviousCase(),
    player: {
        y: selectedCase.y,
        x: selectedCase.x
    }
});

(That said, keep in mind that clean, readable code is often the more important thing to strive for - if separating it out onto different lines is more readable, don't be afraid to do so. Only code golf if code-golfing is the objective)

Another option is:

const {
    x,
    y
} = selectedCase;
setMap({
        ...removePreviousCase(),
        player: {
           x,
           y
        });

Upvotes: 5

Related Questions