Avoid Accidental Returns of New State by using the void Keyword

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

A small caveat with Immer is that arrow functions that consist of just an expression, and not a function block, always return a value.

In this lesson we will show that in these cases the void keyword can be used to avoid accidentally returning new state in addition to modifying the draft.

Instructor: [0:00] You might have noticed that draft isn't just here in our handle or a set function. A producer should always do either of two things. Either it should modify the draft, or it should return an entirely new state, but it should never do both.

[0:16] What happens if you're doing both? Let's remove the accolades over here. Now, the return of our recipe will be to return of push. If we save this, and we again add Lego boost, our application now horribly crashes. Why? Either a producer should return an new value, or it should modify a draft. It shouldn't be doing both.

[0:37] What our recipe does over here, it's modifies a draft, it's as another GIF. Also, it returns the length of the array because that is what pushed us by default as return. The new states will just be simply the number three which obviously doesn't work as three doesn't have users and GIFs and etc.

[0:58] However, in some cases, it's really nice to have those short, one-liner functions that take an expression without body to do some updates. For that, there's one neat, little trick, is to use the keyword void. Void is quite an unknown keyword in JavaScript. What it does is it takes expression on the right hand and it always returns and it finds.

[1:19] Basically, it behaves the same as a function that doesn't return anything, and it fixes our problem. Now, in this specific example, it doesn't add that much, and I would give, for example, by using accolades.

[1:29] However, if you have one-liner updates functions, it can be quite a new trick.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today