Simplify optimistic rendering with redux-optimist library
The redux-optimist library has been extremely helpful to me and I’d like to share that with you. I’ve designed a simple tutorial where I’ll walk you through how to set up and use the middleware. We’re going to use a sweet pokemon API as our demo practice. We’ll fetch this Pikachu and optimistically evolve it to Raichu. If the request fails, then we’ll devolve back to Pikachu.
1) Let’s install the dependencies we need, in your terminal:
yarn create react-app app-name
cd app-name
yarn add react-dom
yarn add react-router-dom
yarn add react-redux
yarn add redux
yarn add redux-thunk
yarn add lodash
2) Follow along to set up Redux, or skip ahead to step 3 if you have your own preferred redux setup.
a. open src/index.js
b. create action file, in your terminal: touch src/pokemonActions.js && open src/pokemonActions.js
c. create reducer file, in your terminal: touch src/reducer.js && open src/reducer.js
d. open src/App.js
e. open src/App.css
3) Let’s install redux-optimist now, in your terminal:
yarn add redux-optimist
4) I suggest commiting here, that way you can see your git diff before implementing redux-optimist
and after redux-optimist
:
git add . && git commit -m "feat(redux): finished setting up redux"
5) Modify our pokemonActions.js
to create new actions and pass some responsibility to the redux-optimist
library:
6) Create a middleware
folder and create this file getRaichu.js
inside the folder, in your terminal: mkdir src/middleware && touch src/middleware/getRaichu.js && open src/middleware/getRaichu.js
7) Import and use the getRaichu.js
middleware in our index.js
:
8) Modify our reducer.js to work with the new actions and middleware:
9) Now in your terminal, yarn start
and open up your console. I’ve placed a couple console.log
to help observe the procedure of our action, middleware, and reducer.
You’ll notice that the object in GET_RAICHU_BEGIN
is a mock Raichu where I only supplied the name and image, then when the request succeeds, GET_RAICHU_COMPLETE
sends the full object returned from the API to update our store.
10) Now let’s imitate a failed request by commenting out the fetch request on line 32 in getRaichu.js
and commenting in line 33.
This time you will see that we optimistically render Raichu until the request comes back as a fail. The store will automatically revert back to Pikachu. At this time we also capture the error from the failed request and display it to the user. So moral of the story, don’t evolve your Pikachu :)
Here are screenshots of the git diff from our usual redux
to implementing redux-optimist
:
That’s it for optimistic rendering with the redux-optimist library! Hope this was helpful!
Bring your friends and come learn JavaScript in a fun never before seen way! waddlegame.com
Top comments (0)