Dan Zuzevich
Dan Zuzevich

Reputation: 3831

Javascript function syntax in React/Redux

This may even be more of a generic Javascript(possibly es6) question, but here lets see how it plays out.

I encounter this type of syntax daily, and am beginning to become annoyed that I do not understand how this stuff is working under the hood:

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore)

I can see that applyMiddleware is obviously a function, that in this example, is taking reduxThunk as an argument. However, I have no clue what createStore is doing sitting in parentheses next to it.

Same can go for this example, where I am confused about what's going on with UserList:

export default connect(mapStateToProps)(UserList)

Could anyone explain to me what is going on here? An explanation of both would be appreciated, as they both serve different purposes, and one ends up being an expression.

Upvotes: 1

Views: 66

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282080

I is a way of calling a function that returns another function so the definition of applyMiddleware will look something like

const applyMiddleware = (middleware) => {
     return (store) => {
          // some modification here
          return somethinghere;
     }
}

so the two argument that you see are first to the outer function and then to the returned function.

Similarly connect also returns a function the first et of arguments are to the connect function and the second set of arguments to the function returned by it.

The call

export default connect(mapStateToProps)(UserList)

is equivalent of

var connectStateProps = connect(mapStateToProps);
export default connectStateProps(UserList);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075597

This:

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore)

is exactly the same as this:

const temp = applyMiddleware(reduxThunk);
const createStoreWithMiddleware = temp(createStore);

(But without the temp variable.)

The code is calling applyMiddleware with the argument reduxThunk; applyMiddleware returns a function. Then, the code is calling that function with the createStore argument.

Here's a simple example with no libs or similar:

function createAdder(valueToAdd) {
    return function(valueToAddTo) {
        return valueToAddTo + valueToAdd;
    };
}

// Doing it all at once
const result1 = createAdder(5)(10);
console.log(result1); // 15

// Doing it step by step
const addFiveTo = createAdder(5);
const result2 = addFiveTo(10);
console.log(result2); // 15

Upvotes: 3

Related Questions