How 💩 dad jokes helped me better understand immutable data

Author

Spencer Carli

Developer, cat dad, and devout pizza lover. Teaching at React Native School and building apps with Handlebar Labs.

I recently started working on a course regarding React Native and push notifications (how to, strategy, etc.).

With that, I had to put together an example app — I decided on an app that will show you some 💩 dad jokes. You can swipe through them in an ever-so-popular Tinder like card interface.

The app fetches 3 jokes and then, as you swipe jokes away, I make a request for new ones — adding those new jokes to my array of 💩 dad jokes.

It didn’t all work out perfectly though. The issue? When I got a new question it would bring me back to the very first joke. Like this…

null

Dem jokes though

So, what’s happening? Initially I request 3 jokes before we render any. This gives me an array of jokes like this:

If I get rid of the request-new-joke-on-swipe functionality everything works fine.

null

That makes me think the issue is related to that array changing…

Initially I had assumed the swiping component I was using (react-native-deck-swiper) could handle the changing array and would append those results to the existing stack.

That wasn’t true — and wasn’t a good assumption on my part.

Since I’m creating a new jokes array and saving it to state on each new joke request (this is the right way to do it since you don’t want to mutate existing state) I needed to better handle this.

What I found was that, each time I got a new joke, the swiper component re-rendered and, by default, the swiper component would render the card at index 0 — which was always the very first joke in my array.

Fortunantely, you can override this via a prop of cardIndex so all I have to do is

  1. Track the current card index
  2. Pass that index to my swiper component

Easy. Each time I swipe a card away I’ll increment my cardIndex, stored in component state, and then pass this.state.cardIndex to the Swiper component.

That results in the following interaction

null

Now you can have quick access to all the 💩dad jokes you can handle

You can find the complete code on Snack.

Have questions about react native & push notifications? Let me know!