r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

Show parent comments

34

u/snorkl-the-dolphine Mar 18 '19

This can cause issues of it runs twice in quick succession. The safe way to do this is:

this.setState(({toggle}) => {toggle:!toggle});

16

u/[deleted] Mar 19 '19

this && setState? What is this, 2018? šŸ˜„

4

u/beforan Mar 19 '19

Oh shit, I guess I have to do no work today while I read about hooks and refactor some components

0

u/[deleted] Mar 19 '19

[deleted]

0

u/SalamiJack Mar 19 '19 edited Mar 19 '19

I mean, technically you're still "setting state", but it won't be called setState when using hooks. You're typically meant to call useState multiple times per each individual piece of state you track, rather than attempting to modify one big state object.

For example, a component that keeps track of an internal count and whether or not to show/hide a popup would use the state hook like:

const [count, setCount] = useState(0);

const [isPopupVisible, setIsPopupVisible] = useState(false);

Edit: No idea why I’m being downvoted.

0

u/[deleted] Mar 19 '19

Yeah fair, was just being goofy, though the hooks example would no longer work with partial state changes a la classic setState.

2

u/NoInkling Mar 19 '19

Careful with syntax! You need a set of parens around the object:

this.setState(({toggle}) => ({toggle: !toggle}))

Even worse, your version won't throw a syntax error because toggle: is interpreted as a label, making it a pretty insidious bug (React should hopefully catch it though).

1

u/disclosure5 Mar 19 '19

I get why it's a problem, can I get a reference or ELI5 on why that solution is any safer?