Last active
March 28, 2022 21:58
-
-
Save ericelliott/e30bd9c5ecbbebd50986058189e8e985 to your computer and use it in GitHub Desktop.
Impure Action Creator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Action creators can be impure. | |
export const addChat = ({ | |
// cuid is safer than random uuids/v4 GUIDs | |
// see usecuid.org | |
id = cuid(), | |
msg = '', | |
user = 'Anonymous', | |
timeStamp = Date.now() | |
} = {}) => ({ | |
type: ADD_CHAT, | |
payload: { id, msg, user, timeStamp } | |
}); |
The first "object" is deconstructing and setting defaults on the single first argument given. Which is itself given a default of an object as a default after the } =
.
So this function expects a single param which is an object containing id, msg, user, and timestamp
. If the object is not given (aka the function runs with only undefined as an argument or no argument. Then the first argument will default to an empty object... out of which the first "object" will be deconstructed for each value of or set with a default.
So addChat()
is the same as
addChat({ id: cuid(), msg: "", user: "Anonymous", timestamp: ${currentTime()} })
But if user is given it will use the user or if msg is originally included in the argument given-- it will use the msg originally given:
addChat({ id: cuid(), msg: "blah blah", user: "[email protected]", timestamp: ${currentTime()} })
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What does the
} = {}
do? I'm a bit confused about that. It seems like it just makes the first object an empty object{}
.