Explaining Redux Through A Side Project

One of my first coding projects ever was a CLI app that was connected to a cocktails API. As I reviewed Redux, I decided to remake that app, but this time, in REDUX. This small project was a way for me to better understand the redux cycle on a smaller scale.

Image for post
Image for post
https://dev.to/radiumsharma06/abc-of-redux-5461

A user will interact with the app in some way, like clicking a button. This will trigger an action, which is sent to the reducer, which updates the store, which contains the state, which defines the user interface(UI).

My goal was to create an app that allowed the user to click a button, and be given a random drink name and the associated photo. I began by creating the store in the index.js file. I imported Provider, which connects store and react, and imported createStore and applyMiddleware from redux. I created a store, then wrapped my App in that store.

Image for post
Image for post
https://github.com/jkhaha/cocktail-generator/blob/master/src/index.js

In my store file, I had an action file and a reducer file. In action, I had my action creators and my thunk creators. I created an action called getCocktail and a thunk creator called loadCocktail.

Image for post
Image for post

In my cocktail component, I used mapDispatchToProps to map loadCocktail to props. When a user clicks the SURPRISE ME button, loadCocktail is invoked and it fetches a random cocktail from the API. This response is then jsonified and dispatched to the reducer using getCocktail. The type of the action is “GENERATE_COCKTAIL”, and the reducer checks the type to see what it should do.

on line 11, the onClick function is this.props.loadCocktail which is from the mapDispatchToProps
Image for post
Image for post
reducer which uses a switch case to determine what action to carry out

The reducer receives an action and sends it through the switch statement to see which case matches the type. This reducer is small because this is a small app, so the case is right there on line 8. The reducer then updates the store, which is what contains state. This new state causes a re-render of the portions that change, which changes what the user sees!

Image for post
Image for post
https://day-one-cocktail-generator.herokuapp.com/

The app is deployed!

Written by

Fullstack Engineer @ Forbes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store