Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active March 28, 2022 21:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericelliott/e30bd9c5ecbbebd50986058189e8e985 to your computer and use it in GitHub Desktop.
Save ericelliott/e30bd9c5ecbbebd50986058189e8e985 to your computer and use it in GitHub Desktop.
Impure Action Creator
// 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 }
});
@ColdSauce
Copy link

{
  // cuid is safer than random uuids/v4 GUIDs
  // see usecuid.org
  id = cuid(),
  msg = '',
  user = 'Anonymous',
  timeStamp = Date.now()
} = {}

What does the } = {} do? I'm a bit confused about that. It seems like it just makes the first object an empty object {}.

@zargold
Copy link

zargold commented Nov 4, 2017

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: "me@me.com", timestamp: ${currentTime()} })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment