Asynchronous Actions with Redux -- Polycasts #62

Chrome for Developers · Intermediate ·🌐 Frontend Engineering ·9y ago

Key Takeaways

Explains asynchronous actions with Redux using Redux Thunk

Full Transcript

Hey everybody, what's up? It's Rob Dodson. Welcome back to the Polycast show. So today we're going to be talking about doing a synchronous actions using Polymer Redux. And to do this, we're going to use a little library called Redux Thunk. So Redux Thunk kind of in a nutshell basically teaches Redux to treat certain kinds of uh actions uh as functions. So I can give it a function and I'll run it as if it's any other action. And inside of that function I can do all sorts of cool asynchronous work and I can share those functions amongst my different components. So that way I don't have to like duplicate that work all over the place. So I'll teach you how to do that as well today. So follow me over here to my text editor. And the first thing we're going to do actually is uh is bust open the terminal and inside of our project we're just going to npm install-save redux funk. Now, I've already got um Polymer Redux and I've got Redux installed from the previous episode. So, if you haven't seen that episode, definitely go check that out. We'll include a link to it. Maybe a little little picture and picture window will pop up somewhere. Uh go check out that episode. Uh over here though, we're just going to install Redux Lunk from npm. Uh I've already got it set up, so we're good to go. Uh the next thing I'm going to do is go over to my text editor. And here, I'll bump this up a little bit to make it a bit easier to read. And I'm going to start off by creating a Redux store. So here I am importing polymer redux. And then I've got a script element inside of this HTML import called redux store. And the first thing I usually do is create some initial state. So I'll say cost initial state. And uh what we're going to build today is is a really really really simple example. Um it's just going to be like a little form that someone can type in a username and click sign up. And then it's going to go off and do a little bit of asynchronous work. And when that work is done, it'll display that person's name. So while it's doing the work, it'll be like loading. And then once they're done, it'll be like welcome so and so, you know, whatever username they put in. So uh our initial state here, we'll say loading is false. And uh we will say we'll give it a name. That's good. Initial state. Say loading is false. And username equals null. Okay, cool. So once I have my initial state in place, the next thing I want to do is write a reducer. So reducer uh is going to take in the actions that are dispatched and modify our state. So we'll say reducer is a function that takes state and action as arguments. Uh we'll say hey if there was no state passed in then we will return turn our initial state. Otherwise, we're going to switch on the action type. So, we'll switch action.type. So, the first action that we'll be looking for is uh sign up started. Okay, we're going to just return um our state object. And as is sort of like the typical Redux pattern, we're going to make a clone of that state object and we're going to uh mutate the uh the loading flag inside of there. So, we'll say return object assign and we'll pass in an empty object. We'll pass in our state to copy it over into that empty object. And then we will pass in uh loading true. Okay. So, someone says signup started. We're just going to display a loading message. Um the other thing we're going to do here is we'll have sign up completed. Okay. We're going to do something very similar. We're going to return object. fine, pass in empty object, pass in state, and then the two things we're going to do here is we're going to set loading back to false. And we're also going to assume that someone is going to pass in the username as part of that action. So we're going to say username is equal to action username. Okay, so this is our very simple reducer just handling a couple of sort of like asynchronous states. All right, once we have that in place, uh, we need to re, uh, we need to create our store. Do it this way so I don't make a typo. There we go. So, store equals redux create store. We're going to pass it the reducer. And then we're going to uh call Redux apply middleware and give it this Redux thunk thing. And again, Redux thunk is going to uh teach our store and and and our dispatcher to take a function in certain cases and treat it as if it is an action. So you can still dispatch regular actions just like we did in the previous episode. We can also dispatch a function now or give it to the dispatcher and we'll run that function and we'll actually sort of like treat it like it's its own action. But that way we can do a bunch of async work inside of that function. So we're going to create our store that way. Uh we're going to create a redux behavior. So we'll say const redux behavior equals polymer redux. We'll pass it the store. Okay. Um, and then I want to create another behavior that's going to contain my asynchronous actions. So, in the last episode, one of the things I did was I actually kind of like hardcoded the action dispatch to the component that I was working with. Um, and you know, the issue with that is if you have more than one component that needs to dispatch the same action, that would be sort of annoying and repetitive to have to like implement that in every single component. So what we can do is we can create a behavior for the actions object that polymer redux uses and we can share that amongst any sort of components that want to dispatch these particular actions. So I'm going to create a new behavior called async actions behavior. Uh this is just going to be an object. It is going to have an actions object on it. And uh the action that we're going to be doing is just going to be called sign up with timeout. So, we're not actually going to like go talk to an API or anything to simulate an asynchronous action. I'm just going to write a set timeout inside of this action creator. Um, so our action will be sign up with timeout. Uh, it's a function that is going to take as an argument a username and it's going to return a function that takes a dispatcher as an argument. So, that's going to be the actual Redux dispatcher. Uh basically Redux thunk is going to handle passing that dispatcher into this return function for us. And then we just want to dispatch a few actions. So the first thing we'll do is we'll call uh dispatcher.dispatch. Uh let's see. Let make sure I didn't do this. Let make sure I did this right here really quick. Uh so we're passing in dispatch. Oh. Ah. This is what I got wrong. I knew I was doing something wrong. Instead of passing in the dispatch for object, we're actually dispatching or we're just passing in the dispatch method. So we don't actually have to, you know, say dispatcher. Dispatch, we just say dispatch. And the first thing we'll do is we will dispatch uh an action or sorry an action whose type is sign up started. Right? So this is going to kick off our asynchronous process. Uh then we're going to do a set timeout. So set timeout, give it a function here. Say wait maybe like 3,00 seconds. All right. And then inside of this function, we're going to dispatch another action. This time we'll assume that our, you know, asynchronous signup process is completed. Our server responded or whatever. So we'll say sign up completed. And then we're going to say username is equal to this username value that was passed in here. So username is equal to username, right? Okay, I think that looks about right to me. So what we're going to be able to do now is share this behavior amongst components and then those components can just say uh this.dispatch sign up with timeout and they can like pass in a username value and it'll go do all this asynchronous work or whatever. Um and then eventually that will update our state. So let's actually go implement that. Uh I'm going to create a little signup form component. So I've got a signup form.html HTML that I've created here. I'm already importing Polymer. I'm already importing our our Redux store. Right? So, I will just uh stub out Polymer element called signup form. Uh inside of here, we're going to have a label for our our username field. So, let's see. Input type equals text. So, we'll say username. Fill that in there. And then we'll have a button where we say sign up. And whenever someone taps this button, we will call our sign up function. Okay. And down here, uh, we're going to implement that sign up function. And this will be pretty straightforward. We're just going to say, uh, so let username equal, let's see, let's give this, uh, input text and ID. So we'll say ID uh you know user or something. So we'll say username equals this dot dollar sign user value. Okay. And then we'll say this.dispatch sign up with timeout. And we'll pass in that username. Now we need to also make sure that we are uh mixing in the correct behaviors for this element. So we you know empower it with cool Redux abilities. So, we'll say behaviors. Is that I'm so going to spell this like wrong. There we go. Okay. Behaviors. Uh, we want to make sure that we put in the Redux behavior. I think it's just called Redux behavior. Let's check our store really quick. So, Redux behavior and async actions behavior. I'm going to copy both of these so that I don't make any typos here. So, drop that in. We'll say I want Redux behavior. Let's say I want async actions behavior. Okay. So now what this has done is if you watch the previous episode, we actually like gave um our action dispatching element an actions object like a properties object. In this case though, we're just sharing that because we've got that async actions behavior and we've already sort of defined the actions object there. So that's just going to get shared with this component. Uh so it can just call dispatch. It can reference this sign up with timeout action creator and then it'll do all this work for us. Okay. So, I think that this looks good so far. Now, um the next thing I want to do is I want to create another element to just sort of like display the state as it's being updated inside of our app. So, I'm going to create another element just called notification bar. So, this notification bar.html. Uh just like the last one, we're going to import polymer. We're going to import the redux store. Let's start to stub this one out. So, we'll say notification bar. This one is actually going to have some properties. So, properties, right? And these are going to be coming from our Redux store. So, the first property is going to just be uh loading type boolean. And then remember from the last episode, the way that we reference something in the Redux store is we use this state path property. So, state path in this case because it's like right on the root uh store object, we can just say the state path is loading. But again, if it was like nested, you know, if it was, you know, at like fu.bar.loading, we could reference it this way using dots. Uh, but we're just going to say loading. And we're also going to say the username is going to be passed in. So that is just going to be a string. And again, the state path for that will just be username right on the root object there. And so I'm just going to do this quick and dirty. Like I'm not going to do a bunch of um, you know, elaborate checks or guards or anything about things being undefined or whatnot. I just want to demonstrate how this works. So, I'm going to write two templates. One that displays a loading message and one that displays the username. Just assuming that, you know, everything works and and is fine and dandy. If it doesn't though, you know, inside of signup form, for instance, you could have um or sorry, inside of this uh uh async actions behavior here, sign up with timeout, you could have error handling inside of here, you could dispatch like an error state action or something like that as well. This is where you would do that work. Uh but in our case, we're just going to keep it, you know, pretty simple. Uh, I'm going to make a couple DOM if templates. So, I say template is DOM if if we are loading. Then we're just going to have a little paragraph. Whoa, that is way more than a paragraph. We'll just have a little paragraph there. There we go. That says loading dot dot dot. Okay. And then we'll drop in another template. is DOM if if we have a username, drop in another paragraph and we'll just say welcome username like that. Okay, so again I'm not doing like a bunch of fancy error checking or anything like that, but I just want to demonstrate how this thing works. Let's go back to our index file. We're going to uncomment these elements. We're going to make sure notification bar is in. We're going to make sure signup form is in. We'll make sure we've got both of them down in the body. And then note here in my script tags what I'm doing. I'm pulling in web components lightjs. I'm pulling in redux and I'm pulling in redux thunk. Remember to pull this in as well. Don't don't don't wire all this up and then be like, why the heck is it not working? So make sure you pull in redux thunk as well. Um, and now I think we've got everything set up. Let's go over here, refresh the page. I'll uh I'll zoom this in so you can see it. Uh, so I'll open the console in case something explodes. That's always good to see if that happens. So, what we want to happen is someone's going to type in their username. They're going to click sign up. It'll put the app in a loading state and then for 3 seconds because we got that set timeout in there, it'll just say loading. And then eventually it'll come back and it'll say welcome and whatever username we type. So, we'll say uh put in Bob Dodd. Bob Dodd. There we go. Sign up. And nothing happens. It's totally broken. Where did we go wrong? All right. Oh, uh let's see. So this dispatch sign up with timeout username. So let's see. Let's just make sure that this is even being called. So we'll log username. Make sure that's being called. So Bob sign up. Okay, that part's working right. Let's make sure in our Redux store actions sign up with a timeout. Oh. Oh. Oh, I knew it. So our notification bar here. I totally forgot to mix in the behaviors. So, I always do this. So, I want to pull in this Redux behavior. It does not need the async actions behavior because it's not dispatching any actions. It's just going to be um displaying whatever we type in. So, let's try this again. So, we'll say Bob do say sign up. It says loading. Tick tick tick tick tick. Boom. Welcome Bob Dodd. All right. So, there you have it. That is a a very uh easy way to add asynchronous actions to your Redux Polymer app. Um I'll include some links down in the show note for some more information on Redux Thunk because it's uh it's cool, but it's also sort of another big topic that is kind of outside of the scope for us to explain in this show, but I'll definitely give you some reading material so you can learn more about it. Uh as always, if you have questions, you can leave them for me down in the comments or hit me up on a social network of your choosing at # askpalymer. As always, thank you so much for watching. I'll see you next time. Hey folks, what's up? It is Rob. Thank you so much for watching this episode. If you'd like to see some more, we got some over there in the playlist. And as always, you can click the little subscribe button to keep getting content every time we push it up to the channel. Uh again, thank you so much for watching.

Original Description

Today we're continuing on with polymer-redux and talking about asynchronous actions. To streamline the process we'll be using an addition to Redux called Redux Thunk. Redux Thunk let's you dispatch a function that can asynchronous fire off actions, kind of like an async action creator. Demo code: https://goo.gl/9j99db Check out the docs for redux-thunk on GitHub: https://goo.gl/HLb0Md Polycasts playlist: https://goo.gl/r5fsMq Polymer Slack: http://bit.ly/polymerslack Subscribe to the Chrome Developers channel: https://goo.gl/OUF4e2
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Chrome for Developers · Chrome for Developers · 0 of 60

← Previous Next →
1 Polymer Performance Patterns (The Polymer Summit 2015)
Polymer Performance Patterns (The Polymer Summit 2015)
Chrome for Developers
2 Polymer Power Tools (The Polymer Summit 2015)
Polymer Power Tools (The Polymer Summit 2015)
Chrome for Developers
3 Chrome Dev Summit 2014 – Chrome Case Studies
Chrome Dev Summit 2014 – Chrome Case Studies
Chrome for Developers
4 Web Directions Code 2015 round up
Web Directions Code 2015 round up
Chrome for Developers
5 Maintainable Code - HTTP203
Maintainable Code - HTTP203
Chrome for Developers
6 iron-ajax… wat?! -- Polycasts #26
iron-ajax… wat?! -- Polycasts #26
Chrome for Developers
7 The Guardian - Supercharged
The Guardian - Supercharged
Chrome for Developers
8 ES2015 (next version of JavaScript), Totally Tooling Tips (S2 Ep1)
ES2015 (next version of JavaScript), Totally Tooling Tips (S2 Ep1)
Chrome for Developers
9 #AskPolymer: Rob answers all the questions ever -- Polycasts #27
#AskPolymer: Rob answers all the questions ever -- Polycasts #27
Chrome for Developers
10 The Future of JavaScript - HTTP203
The Future of JavaScript - HTTP203
Chrome for Developers
11 Data Binding 101 -- Polycasts #28
Data Binding 101 -- Polycasts #28
Chrome for Developers
12 The Guardian part 2 - Supercharged
The Guardian part 2 - Supercharged
Chrome for Developers
13 The Future of Web Audio: with Chris Wilson and Chris Lowis
The Future of Web Audio: with Chris Wilson and Chris Lowis
Chrome for Developers
14 Chrome 46: New motion-path animations, client hints and service worker improvements
Chrome 46: New motion-path animations, client hints and service worker improvements
Chrome for Developers
15 Sublime Snippets, Totally Tooling Tips (S2 Ep2)
Sublime Snippets, Totally Tooling Tips (S2 Ep2)
Chrome for Developers
16 #AskPolymer: How do you make the show? -- Polycasts #29
#AskPolymer: How do you make the show? -- Polycasts #29
Chrome for Developers
17 Critical Path CSS, Totally Tooling Tips (S2 Mini Tip #1)
Critical Path CSS, Totally Tooling Tips (S2 Mini Tip #1)
Chrome for Developers
18 Binding to Objects -- Polycasts #30
Binding to Objects -- Polycasts #30
Chrome for Developers
19 Player FM - Supercharged
Player FM - Supercharged
Chrome for Developers
20 Where’s the Designer? #AskPolymer -- Polycasts #31
Where’s the Designer? #AskPolymer -- Polycasts #31
Chrome for Developers
21 Jake Beats Wikipedia - HTTP203
Jake Beats Wikipedia - HTTP203
Chrome for Developers
22 Supercharged Observers! -- Polycasts #32
Supercharged Observers! -- Polycasts #32
Chrome for Developers
23 Jai's Web blog - Supercharged
Jai's Web blog - Supercharged
Chrome for Developers
24 Windows Command-line Tooling, Totally Tooling Tips (S2, Ep4)
Windows Command-line Tooling, Totally Tooling Tips (S2, Ep4)
Chrome for Developers
25 What about internationalization? #AskPolymer -- Polycasts #33
What about internationalization? #AskPolymer -- Polycasts #33
Chrome for Developers
26 Developing for Billions (Chrome Dev Summit 2015)
Developing for Billions (Chrome Dev Summit 2015)
Chrome for Developers
27 Google+ Performance Improvement Comparison
Google+ Performance Improvement Comparison
Chrome for Developers
28 Deploying HTTPS: The Green Lock and Beyond (Chrome Dev Summit 2015)
Deploying HTTPS: The Green Lock and Beyond (Chrome Dev Summit 2015)
Chrome for Developers
29 Progressive Web Apps (Chrome Dev Summit 2015)
Progressive Web Apps (Chrome Dev Summit 2015)
Chrome for Developers
30 Instant Loading with Service Workers (Chrome Dev Summit 2015)
Instant Loading with Service Workers (Chrome Dev Summit 2015)
Chrome for Developers
31 Increase Engagement with Web Push Notifications (Chrome Dev Summit 2015)
Increase Engagement with Web Push Notifications (Chrome Dev Summit 2015)
Chrome for Developers
32 Engaging with the Real World: Web Bluetooth and Physical Web (Chrome Dev Summit 2015)
Engaging with the Real World: Web Bluetooth and Physical Web (Chrome Dev Summit 2015)
Chrome for Developers
33 Asking for Permission: respectful, opinionated UI (Chrome Dev Summit 2015)
Asking for Permission: respectful, opinionated UI (Chrome Dev Summit 2015)
Chrome for Developers
34 Polymer - State of the Union (Chrome Dev Summit 2015)
Polymer - State of the Union (Chrome Dev Summit 2015)
Chrome for Developers
35 Building Progressive Web Apps with Polymer (Chrome Dev Summit 2015)
Building Progressive Web Apps with Polymer (Chrome Dev Summit 2015)
Chrome for Developers
36 Introduction to RAIL (Chrome Dev Summit 2015)
Introduction to RAIL (Chrome Dev Summit 2015)
Chrome for Developers
37 DevTools in 2015: Authoring to the max (Chrome Dev Summit 2015)
DevTools in 2015: Authoring to the max (Chrome Dev Summit 2015)
Chrome for Developers
38 RAIL in the real world (Chrome Dev Summit 2015)
RAIL in the real world (Chrome Dev Summit 2015)
Chrome for Developers
39 #ChromeDevSummit talks are up - W00T! -- Polycast #34
#ChromeDevSummit talks are up - W00T! -- Polycast #34
Chrome for Developers
40 V8 Performance from the Driver's Seat (Chrome Dev Summit 2015)
V8 Performance from the Driver's Seat (Chrome Dev Summit 2015)
Chrome for Developers
41 Quantify and improve real-world RAIL (Chrome Dev Summit 2015)
Quantify and improve real-world RAIL (Chrome Dev Summit 2015)
Chrome for Developers
42 Owning your performance: RAIL (Chrome Dev Summit 2015)
Owning your performance: RAIL (Chrome Dev Summit 2015)
Chrome for Developers
43 HTTP/2 101 (Chrome Dev Summit 2015)
HTTP/2 101 (Chrome Dev Summit 2015)
Chrome for Developers
44 Leadership Panel (Chrome Dev Summit 2015)
Leadership Panel (Chrome Dev Summit 2015)
Chrome for Developers
45 Build Processes, Totally Tooling Tips (S2, Ep 5)
Build Processes, Totally Tooling Tips (S2, Ep 5)
Chrome for Developers
46 Accessibility (Chrome Dev Summit 2015)
Accessibility (Chrome Dev Summit 2015)
Chrome for Developers
47 Binding to Arrays -- Polycasts #35
Binding to Arrays -- Polycasts #35
Chrome for Developers
48 HTTP2 - HTTP203
HTTP2 - HTTP203
Chrome for Developers
49 Chrome 47: Splash Screens, requestIdleCallback and better desktop notifications (New in Chrome)
Chrome 47: Splash Screens, requestIdleCallback and better desktop notifications (New in Chrome)
Chrome for Developers
50 Call For Submissions - Supercharged
Call For Submissions - Supercharged
Chrome for Developers
51 Cross Device Testing, Totally Tooling Tips (S2 Ep6)
Cross Device Testing, Totally Tooling Tips (S2 Ep6)
Chrome for Developers
52 Testing AJAX with Web Component Tester -- Polycasts #37
Testing AJAX with Web Component Tester -- Polycasts #37
Chrome for Developers
53 Slack: Extended Xmas Special - Supercharged
Slack: Extended Xmas Special - Supercharged
Chrome for Developers
54 Browser testing with Travis & Sauce Labs -- Polycasts #38
Browser testing with Travis & Sauce Labs -- Polycasts #38
Chrome for Developers
55 Optimize for production with Vulcanize -- Polycasts #39
Optimize for production with Vulcanize -- Polycasts #39
Chrome for Developers
56 Highlights from Chrome Dev Summit 2015
Highlights from Chrome Dev Summit 2015
Chrome for Developers
57 Chrome 48: Custom buttons in notifications, DevTools Security panel, and Presentation mode
Chrome 48: Custom buttons in notifications, DevTools Security panel, and Presentation mode
Chrome for Developers
58 Crisper: Protecting your Polymer app with CSP -- Polycasts #40
Crisper: Protecting your Polymer app with CSP -- Polycasts #40
Chrome for Developers
59 How do I use Sass with Polymer? #AskPolymer -- Polycasts #41
How do I use Sass with Polymer? #AskPolymer -- Polycasts #41
Chrome for Developers
60 Colors – DevTools Tonight #0 (Pilot)
Colors – DevTools Tonight #0 (Pilot)
Chrome for Developers

Related Reads

Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch →