We're hiring
Products

Channels

Beams

Chatkit

Textsync

preview
DocsTutorialsSupportCareersPusher Blog
Sign InSign Up
Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing

Textsync

preview

Collaborative, realtime editing made easy

Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Sign InSign Up

Create a live workout tracking app with React Native

  • Wern Ancheta
October 22nd, 2018
You will need git, Node and Expo installed on your machine. Some knowledge of React Native is required.

In this tutorial, we’ll be creating a realtime workout tracking app with React Native and Pusher.

Prerequisites

Basic knowledge of React Native, React Navigation, and ES6 syntax is required.

We’ll also be using Redux. I’ll add as much detail as I can on what’s going on with all the Redux code, but you should at least be familiar with how Redux works.

We’ll be using Expo in order to easily test the app on multiple devices. Install Expo on your computer, then download the Expo client app for your iOS or Android device.

These are the package versions used in creating the app:

  • Node 8.3.0
  • Yarn 1.7.0
  • Expo CLI 2.1.2
  • Expo SDK 30.0.0
  • Pusher 4.3.1

It’s always recommended to use the most recent stable versions, but in case the app doesn’t work for you, you can use the versions above to ensure we have the same environment.

Lastly, you must have a Pusher and an ngrok account.

App overview

The app that we will be creating is for gym buddies who are working out in a different gym. They can use it to keep track of their buddy’s workout even if they are away from each other.

The app has two tabs: one for logging their own workout, and another for tracking the workout of their buddy. Users can both log and track at the same time. This makes it possible for users to compete on who can make the most number of sets and reps for each exercise they choose.

Upon opening the app, users will be greeted with the logging tab. This is where they can log their workouts. They’ll be automatically assigned a unique username. When they click on their username, it will be copied to the clipboard so they can easily share it with their buddy:

This is how it looks like when their buddy subscribes. Subscription can be done in the tracking tab. All they have to do is enter their buddy’s username and click on the right arrow:

This is how it looks like when a user adds an exercise and a set:

Once an exercise or set has been added, it will show in the list below the username. The number at the top of the circle is the weight, and the number inside it is the number of reps for that set. When the user clicks on the circle, the reps is incremented by one:

The tracking tab in their buddy’s screen is automatically synced with the exercise and sets the user has added:

You can view the source code of this app on this GitHub repo.

Creating a Pusher app

On your Pusher dashboard, create a new app and name it RNWorkout. Once created, enable the client events in the App Settings tab:

Client events allow us to emit messages directly from the app. Because normally, messages are only emitted from the server. This time, we’ll only be using the server to authenticate the user. This authentication process allows us to make requests directly from the app.

Clone the app

Start by cloning the repo:

    git clone https://github.com/anchetaWern/RNWorkout.git

Switch to the starter branch and install both the app and server dependencies:

    cd RNWorkout
    git checkout starter
    yarn install
    cd server
    npm install

The starter branch contains a minimal version of the app where the screens, components, helper functions, styles, and the server code has already been added. This makes it easy for us to focus on the main subject of this tutorial, and that is how to work with Redux and Pusher Channels.

Starter code tour

Before we proceed with writing some code, let’s first do a quick tour of the code we have on the starter branch.

Helpers

The app/helpers folder contains two helper files for generating unique ID’s (uniqid.js) and usernames (uniqname.js). The unique ID’s are used as a unique identifier for the exercises and sets.

Server

The server folder contains the code for the server component of the app. This server is for authenticating the user when they initialize a new Pusher connection. No further updates are required inside this folder except for the server/.env file. We’ll update it later once we run the app.

Modals

The app/modals folder contains the code for the add exercise and add set modals. These modals are used for logging a new exercise and adding a set to a specific exercise. We will be updating the AddExerciseModal.js and AddSetModal.js later. This is to add the code for dispatching actions that will modify the store.

Components

The app/components folder contains all the components that the app is using. This includes the following:

  • AlertBox - for showing messages enclosed inside a box.
  • IconButton - for showing buttons with an icon in them.
  • SetContainer - for showing the individual sets (the gray circles with a number inside and below them).
  • List - serves as a container list for the SetContainer component.
  • ConnectedFlatList - for showing all the workout data (exercises and sets).

Among the components above, we’re only going to update the ConnectedFlatList (app/components/ConnectedFlatList/ConnectedFlatList.js). As it is right now, it won’t really render anything. We have to turn it into a “connected” component so it will automatically re-render once the relevant data in the store is updated.

Screens

We only have one screen because the logging and tracking features are too similar to have their own screen. If you open the Root.js file, you’ll see that we’re only using the LogWorkout screen:

    import LogWorkoutScreen from "./app/screens/LogWorkout";

    const LogStack = createStackNavigator(
      {
        Log: LogWorkoutScreen
      },
      { initialRouteName: "Log" }
    );

    const TrackStack = createStackNavigator(
      {
        Track: LogWorkoutScreen
      },
      { initialRouteName: "Track" }
    );

We will be updating the app/screens/LogWorkout.js file later because that’s where we need to link everything up.

Build the app

Now we’re ready to build the app. Here’s what we’ll be doing through the rest of the tutorial:

  • Add the actions.
  • Add the reducers.
  • Dispatch an action for adding a new exercise to the store when the user adds a new exercise.
  • Dispatch an action for adding a new set to the store when the user adds a new set.
  • Initialize Pusher.
  • Subscribe user to their own channel so they can emit client events.
  • Subscribe to another user so they can listen for client events emitted by that user.
  • Emit a client event on the channel when a new exercise or set is added by the user.
  • Listen for client events so the tracking tabs UI is synced to that of the user being followed.

The steps above aren’t ordered in a specific way. Most likely, you’ll have to switch between each of them as you’re testing the app. For this tutorial, I recommend you to start the app even if it’s not fully working yet. This allows you to easily see the effects of the code you’re adding, and not simply copy-pasting it:

    expo start

Let’s make this as hands-on as possible. I’ll first mention what needs to be done so you can try on your own, and then you can peak at the code either here or in the GitHub repo if you’re not sure what to do. I’ve also added “todo” comments in the starter code as a guide on where you should put a specific code. Feel free to browse around the code whenever you see “our task is to…” or “next, we need to..” as that’s the cue for when we’ll start adding the code. Try to figure out on your own first before you proceed.

We’ll work on the functionality for logging workouts first. That will be the first screen that you see when you run the app. Right now, we only have the following:

The username is generated, and it can be copied to clipboard, but that’s it. Nothing you can really do in this tab (logging tab) right now.

Add the actions

Our first task is to figure out how to make the add exercise modal visible so we can enter the exercise we want to add.

My usual workflow when working with Redux is to first figure out what the global app state will look like. But before we can do that, we first need to determine the actions that can be done throughout the app in relation to how it affects the UI:

  • Open or close modals.
  • Add an exercise.
  • Set the current exercise.
  • Add a set.
  • Increment set.

Note that I’ve excluded actions that are only applicable to a specific component. Here’s a good rule of thumb to determine if something is an action or not:

If the rest of the app’s UI isn’t affected if the value of a specific piece of data is updated, then it’s not an action.

For this app, non-actions include:

  • Entering the name of the exercise.
  • Entering the weight of a set.

Both instances don’t update the app’s UI in a way that affects the whole app, so the state for those can be managed within the component level.

Go ahead and create an app/actions folder. Inside it, create a types.js file and define all the actions that we came up with. This will help us avoid typos when working with actions:

    // app/actions/types.js
    export const ADDED_EXERCISE = "added_exercise";

    export const ADDED_SET = "added_set";
    export const INCREMENTED_SET = "incremented_set";

    export const MODAL_TOGGLED = "modal_toggled";
    export const SET_EXERCISE = "set_exercise";

Next, define the action creators. These are functions that will return the data needed by each action. Each action type will have its own function, which returns it as the type property:

    // app/actions/index.js
    import {
      ADDED_EXERCISE,
      ADDED_SET,
      INCREMENTED_SET,
      MODAL_TOGGLED,
      SET_EXERCISE
    } from "./types";

    export const addedExercise = (exerciseID, exerciseName, user = "me") => {
      return {
        type: ADDED_EXERCISE,
        id: exerciseID, // a machine-friendly version of the exercise name
        exercise: exerciseName, // name of the exercise (e.g. front squat)
        user: user 
      };
    };

    export const addedSet = (setID, exerciseID, weight, user = "me") => {
      return {
        type: ADDED_SET,
        id: setID, // unique ID for the set
        exercise_id: exerciseID, // used for determining which exercise to put the set under
        weight: weight, // how heavy is the weight being lifted (usually in lbs)
        reps: 1, // default number of repetitions for a new set
        user: user
      };
    };

    export const incrementedSet = (setID, reps, user = "me") => {
      return {
        type: INCREMENTED_SET,
        id: setID, // unique ID for the set
        reps: reps, // repetitions performed for this set
        user: user
      };
    };

    export const modalToggled = (modalName, visibility) => {
      return {
        type: MODAL_TOGGLED, 
        modal: modalName, // addExerciseModal or addSetModal
        visibility: visibility // true (visible) or false (not visible)
      };
    };

    // for setting the exercise in which to add a set
    export const setExercise = id => {
      return {
        type: SET_EXERCISE,
        exercise_id: id
      };
    };

Note that the addedExercise, addedSet, and incrementedSet functions have a user parameter which is set to me by default. This allows us to specify which specific app state will the data go. The value of this parameter can either be me or others. me is for the data displayed in the logging tab, while others is for the data displayed on the tracking tab.

Add the reducers

Next, we need to create the reducers. These are responsible for describing how a specific portion of the app state will change. Personally, I create a separate reducer based on the data they’re modifying. In this app, that would be:

  • Exercise reducer (ExerciseReducer.js) - for exercise-related data.
  • Set reducer (SetReducer.js) - for set-related data.
  • UI reducer (UIReducer.js) - for UI-related data. These are usually booleans which hide or show what is seen on the screen (for example, modals and progress loaders).

When it comes to figuring out which reducers to create, anything really goes if you’re only working on a throw-away project to learn a specific technology. But be sure to read about Redux best practices when working in a production app.

Create an app/reducers folder and create the files mentioned above inside it.

Let’s first start with the exercise reducer:

    // app/reducers/ExerciseReducer.js
    import { ADDED_EXERCISE } from "../actions/types";

    import uniqid from "../helpers/uniqid";

    const INITIAL_STATE = {
      exercises: [],
      others_exercises: []
    };

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case ADDED_EXERCISE:
          const key = uniqid();
          const id = action.id;
          const exercise = action.exercise;

          // determine which specific array to update
          const exercises =
            action.user == "me" ? state.exercises : state.others_exercises;

          // create a new array with the new exercise appended to the end of it
          const updated_exercises = exercises.concat({
            key: key,
            exercise_id: id, // machine-friendly version of the exercise name
            exercise_name: exercise
          });

          // return the new state based on which user performed the action
          if (action.user == "me") {
            return { ...state, exercises: updated_exercises };
          }

          return { ...state, others_exercises: updated_exercises };

        default:
          return state;
      }
    };

From the code above, the first step is to define the INITIAL_STATE. Note that this isn’t the initial value for the whole app state. This should only be for the specific data modified by this reducer. In this case, it’s only the exercises (the exercises logged by the current user), and others_exercises (the exercises logged by the user followed by the current user).

Based on the user passed from the action, we get and re-create either the exercises or others_exercises array. Take note of the word “re-create” as we’re not really supposed to modify the state directly, we only replace it with a different value. Redux handles the calculation needed to determine whether the UI should be re-rendered or not. And if you modify the state directly, then it won’t be ensured that that process will work correctly. That’s why we’re using the spread syntax and concat method to avoid updating the state directly.

Next is the set reducer. Again, we’re updating two arrays, one for each user. But this time, our reducer handles two actions, one for when the set is added, and another for when it’s incremented:

    // app/reducers/SetReducer.js
    import { ADDED_SET, INCREMENTED_SET } from "../actions/types";

    const INITIAL_STATE = {
      sets: [],
      others_sets: []
    };

    export default (state = INITIAL_STATE, action) => {
      let sets = [];
      let index = 0;
      let reps = 0;

      let set_name = "sets";
      let current_sets = [];

      switch (action.type) {
        case ADDED_SET:
          current_sets = action.user == "me" ? state.sets : state.others_sets;
          sets = current_sets.concat({
            key: action.id,
            exercise_id: action.exercise_id,
            weight: action.weight,
            reps: action.reps
          });

          const updated_state =
            action.user == "me"
              ? { ...state, sets }
              : { ...state, others_sets: sets };
          return updated_state;

        case INCREMENTED_SET:
          current_sets = action.user == "me" ? state.sets : state.others_sets;
          sets = [...current_sets];
          index = sets.findIndex(itm => {
            return itm.key == action.id;
          });

          reps = action.reps;
          sets[index] = { ...sets[index], reps: reps + 1 }; // add 1 to the current rep

          if (action.user == "others") {
            return { ...state, others_sets: sets };
          }

          return { ...state, sets };

        default:
          return state;
      }
    };

Next is the UI reducer. This is responsible for processing the actions for showing or hiding the modals, and setting the current exercise:

    // app/reducers/UIReducer.js
    import { MODAL_TOGGLED, SET_EXERCISE } from "../actions/types";

    const INITIAL_STATE = {
      ui: {
        current_exercise: "",
        addExerciseModalIsOpen: false,
        addSetModalIsOpen: false
      }
    };

    export default (state = INITIAL_STATE, action) => {
      let ui = {};
      switch (action.type) {
        case SET_EXERCISE:
          ui = { ...state.ui };
          ui["current_exercise"] = action.exercise_id;

          return {
            ...state,
            ui
          };

        case MODAL_TOGGLED:
          ui = { ...state.ui };
          ui[`${action.modal}IsOpen`] = action.visibility;

          const new_state = {
            ...state,
            ui
          };

          return new_state;

        default:
          return state;
      }
    };

The final step is to combine all the reducers into a single file. This allows us to easily supply it when we create the store later:

    // app/reducers/index.js
    import { combineReducers } from "redux";
    import ExerciseReducer from "./ExerciseReducer";
    import SetReducer from "./SetReducer";
    import UIReducer from "./UIReducer";

    export default combineReducers({
      exercises: ExerciseReducer,
      sets: SetReducer,
      ui: UIReducer
    });

Connect the LogWorkout screen to the store

Now that we’ve defined our actions, action creators, and reducers, the next step is to link the LogWorkout screen to the store.

Open app/screens/LogWorkout.js and add the following:

    import { MaterialIcons } from "@expo/vector-icons"; // already added

    // add these
    import { createStore } from "redux";
    import { Provider } from "react-redux";

In the code above, createStore is used for creating the store. Consider the store as the global app state, while the Provider is a helper component that allows us to pass down the store to the component level. This gives us the ability to dispatch actions within this component and allow its child components to also connect to the store.

Next, import the actions and reducers. To create a store we need to pass the combined reducers as an argument. This makes the store aware of which reducers it should use when a specific action is dispatched from the app:

    import {
      modalToggled,
      incrementedSet,
      addedExercise,
      addedSet
    } from "../actions";

    import reducers from "../reducers";
    const store = createStore(reducers);

Next, wrap the whole screen in the Provider component and pass the store as a value for the store prop:

    render() {
      return (
        <Provider store={store}>
          ...
        </Provider>
      );
    }

Once that’s done, we should be able to dispatch actions inside this component’s methods. In this case, we dispatch the action for opening the add exercise modal:

    showAddExerciseModal = () => {
      store.dispatch(modalToggled("addExerciseModal", true));
    };

As the button for opening the modal is inside the header, we need to set the showAddExerciseModal function as a navigation param. That way, we can access it as such from the header:

    componentDidMount() {
      this.props.navigation.setParams({
        showAddExerciseModal: this.showAddExerciseModal
      });
    }

In the navigationOptions, you can now execute the showAddExerciseModal function:

    return {
      headerTitle: `Log Workout`,
      headerRight: (
        <IconButton
          onPress={() => {
            if (routeName == "Log") {
              params.showAddExerciseModal(); // add this
            }
          }}
        />
      ),
    }

When the button is clicked, it should execute the exercise reducer and the app’s state will be modified. Currently, the add exercise modal isn’t really aware of the changes that happen in the store yet, so it won’t really become visible when the button is clicked.

Open the add exercise modal

The next step is to make the add exercise modal into a connected component. That way, it will become aware of the state changes so it can re-render itself when a data it depends on changes.

Open the app/modals/AddExerciseModal.js file. To turn a component into a connected component, we need to use the connect method from react-redux. This allows us to add the functions for mapping specific data in the store as a prop for this component. It also allows us to define functions that we can use inside the component to dispatch actions, as you’ll see later:

    import { connect } from "react-redux";

Next, import the actions for toggling the visibility of the modal, and adding a new exercise:

    import { modalToggled, addedExercise } from "../actions";

Next, scroll to the bottom of the file (right before export default AddExerciseModal) and define the mapStateToProps function. This is used for mapping whichever data we have on the store as a prop for this component. In this case, we only need the ui object from the UI reducer. We use object destructuring to extract it, and the spread syntax to extract the properties that are inside the ui object:

    const mapStateToProps = ({ ui }) => ({
      ...ui
    });

Earlier, in the UI reducer, we defined the following initial state:

    // app/reducers/UIReducer.js
    const INITIAL_STATE = {  
      ui: {
        current_exercise: "",
        addExerciseModalIsOpen: false,
        addSetModalIsOpen: false
      }
    };

mapStateToProps gives us access to those specific properties in the ui object as if it were a prop that’s passed to the component (add exercise modal). To access the current visibility value of the add exercise modal, all we have to do is supply this.props.ui.addExerciseModalIsOpen to the visible prop of the Modal component:

    // app/modals/AddExerciseModal.js
    <Modal
      animationType="slide"
      visible={this.props.ui.addExerciseModalIsOpen}
    >
      ...
    </Modal>

But before we can do that, we first have to connect the component to the store. We can do that with the following code. This returns a “connected” version of the component, one that’s subscribed to the updates made in the store. mapStateToProps gets executed every time there’s an update to the store. If a relevant value is updated, the component is re-rendered because the prop it depends on is directly mapped to a value in the store:

    // app/modals/AddExerciseModal.js
    export default connect(
      mapStateToProps
    )(AddExerciseModal);

    // export default AddExerciseModal; // replace this with the one above

Once that’s done, clicking on the button in the header should make the add exercise modal visible.

If you’re wondering why we used this.props.ui.addExerciseModalIsOpen instead of this.props.addExerciseModalIsOpen, that’s because the data inside the UI reducer lives inside the ui object. We’ve defined this earlier in the reducer’s index file:

    // app/reducers/index.js
    export default combineReducers({
      // ...
      ui: UIReducer
    });

And in the UI reducer, everything lives inside another ui object:

    // app/reducers/UIReducer.js
    const INITIAL_STATE = {
      ui: {
        // ...
        addSetModalIsOpen: false
      }
    };

So to access addSetModalIsOpen, we have to access ui.ui.addSetModalIsOpen from the store. Object destructuring gave us access to the ui object we’ve defined inside app/reducers/index.js file, while the spread syntax gave us access to the ui object defined inside app/reducers/UIReducer.js but not the properties inside of it:

    const mapStateToProps = ({ ui }) => ({
      ...ui // note: spreads the ui object defined in the app/reducers/index.js file. not the ui object in the app/reducers/UIReducer.js
    });

This is why we still had to use this.props.ui.addExerciseModalIsOpen.

Add a new exercise

The next step is to add a new exercise when the add button in the add exercise modal is clicked. Earlier, you learned that to dispatch an action, you first have to import the action creator so you can dispatch it using the dispatch method from the store:

    // app/screens/LogWorkout.js
    store.dispatch(modalToggled("addExerciseModal", true));

The problem we have now is that we have no access to the store or its dispatch method when inside the add exercise modal. The solution for that is the mapDispatchToProps method. It allows us to return functions that are also mapped as props for the component. The dispatch function is automatically passed as an argument to the mapDispatchToProps function, and we can use it to dispatch the action. In this case, we only need the action for toggling the visibility of the modal and adding the exercise:

    // app/modals/AddExerciseModal.js
    // add this right below mapStateToProps
    const mapDispatchToProps = dispatch => {
      return {
        closeModal: () => {
          dispatch(modalToggled("addExerciseModal", false));
        },
        addExercise: (id, name) => {
          dispatch(addedExercise(id, name));
        }
      };
    };

To use mapDispatchToProps, pass it as the second argument for the connect function:

    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(AddExerciseModal);

The next step is to call the two functions (closeModal and addExercise) we just mapped as props:

    addExercise = () => {
      // add these
      if (this.state.exercise_name) {
        const name = this.state.exercise_name;
        const id = name.replace(" ", "_");
        this.props.addExercise(id, name); 

        // already added
        this.setState({
          exercise_name: ""
        });

        this.props.closeModal(); 
      }
    };

Once that’s done, a new exercise should be added to the store every time you click on the add button in the add exercise modal. The modal should also automatically close after that.

Don’t forget to close the modal when the close button is clicked:

    <IconButton
      icon="close"
      color="#FFF"
      size={18}
      onPress={() => {
        this.props.closeModal(); // add this
      }}
    />

Show the exercises

Now that we’ve added the code for creating a new exercise, the next step is to show the exercises that were added. That’s the job of the ConnectedFlatList component.

What we need to do is very similar to what we did in the add exercise modal, so we’ll just breeze through the code. Start by importing all the things we need:

    // app/components/ConnectedFlatList/ConnectedFlatList.js
    import { connect } from "react-redux";
    import uniqid from "../../helpers/uniqid";

    import {
      modalToggled,
      setExercise,
      incrementedSet,
      addedExercise,
      addedSet
    } from "../../actions";

Next, scroll to the bottom of the file and add the mapStateToProps function. While we’re here, let’s also add the data related to the sets:

    const mapStateToProps = state => {
      return {
        exercises: state.exercises.exercises,
        sets: state.sets.sets,
        others_exercises: state.exercises.others_exercises,
        others_sets: state.sets.others_sets
      };
    };

    export default connect(
      mapStateToProps
    )(ConnectedFlatList);

Next, get the relevant exercise data from the props. While we’re here, let’s also extract the sets data:

    render() {
      // add these
      const exercises =
        this.props.user == "me"
          ? this.props.exercises
          : this.props.others_exercises;
      const sets =
        this.props.user == "me" ? this.props.sets : this.props.others_sets;

      // already added
      if (exercises.length) {
        return (
          <FlatList
            data={exercises}
            extraData={sets}
            renderItem={this.renderItem}
            contentContainerStyle={{ paddingBottom: 50, backgroundColor: "#FFF" }}
          />
        );
      }
    }

Take note of the extraData prop that we’ve supplied for the FlatList. We’ve supplied sets to it because the sets data isn’t nested under the exercises array. That means that if we add a new set or increment an existing one, this FlatList won’t really get re-rendered. Supplying sets as an extraData allows us to re-render the main FlatList when the sets data is updated.

Once that’s done, you should now see the exercises being listed as you add them through the add exercise modal.

Open the add set modal

Now that we can add and show exercises, the next step is to show the add set modal.

When the plus button to the right of the exercise name is clicked, it should show the add set modal. To implement that, we need to dispatch the action for toggling the visibility of the add set modal.

Just like what we did earlier in the add exercise modal, we need to use mapDispatchToProps so we can dispatch actions by calling functions that are mapped as a prop:

    // app/components/ConnectedFlatList/ConnectedFlatList.js
    // add these
    const mapDispatchToProps = dispatch => {
      return {
        openAddSetModal: () => {
          dispatch(modalToggled("addSetModal", true));
        },
        setExercise: exercise_id => {
          dispatch(setExercise(exercise_id));
        }
      };
    };

    export default connect(
      mapStateToProps,
      mapDispatchToProps // add this
    )(ConnectedFlatList);

Note that aside from the modalToggled action, we also have setExercise. This is for updating the value of the current_exercise property in the UI reducer so that by the time the user hits the button for adding the set, we can extract this value from the props and supply it as one of the properties for the set to be created.

Next, inside the renderItem method, call the relevant functions you returned in mapDispatchToProps:

    renderItem = ({ item }) => {
      return (
        <View key={item.key} listKey={item.key}>
          <View style={styles.list_item_header}>
            <Text style={styles.list_item_header_text}>{item.exercise_name}</Text>
            <IconButton
              icon="add"
              size={20}
              color="#333"
              onPress={() => {
                if (this.props.user == "me") {
                  // add these:
                  this.props.openAddSetModal(); 
                  this.props.setExercise(item.exercise_id);
                }
              }}
            />
          </View>
        </View>
      );
    }

The next step is to turn the add set modal into a connected component. You should already know how to do this so let’s just look at the code:

    // app/modals/AddSetModal.js
    import { connect } from "react-redux";
    import { modalToggled, addedSet } from "../actions";
    import uniqid from "../helpers/uniqid";


    const mapStateToProps = ({ ui }) => ({
      ...ui
    });

    export default connect(
      mapStateToProps
    )(AddSetModal);


    render() {
      return (
        <Modal
          animationType="slide"
          visible={this.props.ui.addSetModalIsOpen}
          ...
        >
        </Modal>
      );
    }

Once that’s done, the add set modal should become visible when the plus button to the right of the exercise name is clicked.

Add a new set

Adding a new set is very similar to how we added an exercise:

    // app/modals/AddSetModal.js
    const mapDispatchToProps = dispatch => {
      return {
        closeModal: () => {
          dispatch(modalToggled("addSetModal", false));
        },
        addSet: (setID, exerciseID, weight) => {
          dispatch(addedSet(setID, exerciseID, weight));
        }
      };
    };

    export default connect(
      mapStateToProps,
      mapDispatchToProps // add this
    )(AddSetModal);

Take note of how we’re extracting the current_exercise from the props. Earlier, in the ConnectedFlatList, we’ve set the value for this property when the user clicks on the plus button to the right of the exercise name. That’s the purpose of the setExercise action, so we always have the correct value for the exercise_id when we add a new set:

    addSet = () => {
      // add these
      if (this.state.weight) {
        const id = uniqid();
        const exercise_id = this.props.ui.current_exercise;
        const weight = this.state.weight;

        this.props.addSet(id, exercise_id, weight);
        this.props.closeModal();

        // previously added code..
      }
    };

Don’t forget to close the modal when its close button is clicked:

    <IconButton
      icon="close"
      color="#FFF"
      size={18}
      onPress={() => {
        this.props.closeModal(); // add this
      }}
    />

Show the sets

The next step is to show the sets added for a specific exercise. Earlier, we already mapped the current values of the sets and others_sets array in the store over to this component via mapStateToProps. All we have to do now is extract the relevant sets data from the props:

    // app/components/ConnectedFlatList/ConnectedFlatList.js
    renderSets = (exercise_id, key) => {
      const id = uniqid();
      const l_key = exercise_id + ":" + key + ":" + id;

      const sets_data =
        this.props.user == "me" ? this.props.sets : this.props.others_sets;
      const sets = sets_data.filter(item => {
        return item.exercise_id == exercise_id;
      });

      // already added:
      if (sets.length) {
        // ...
      }
    }

Note that the value of this.props.users in the code above is passed as a prop via the standard means (through the component). This is used to determine which specific set data to use (the current user or the user they’re following). The l_key is used as the value for the listKey for the FlatList that will contain each set. We need to supply this because we’re nesting a FlatList within a FlatList. The listKey prop allows React to differentiate between sibling flatlists.

At this point, you should be able to see the sets being listed below a specific exercise when you add them.

Increment a set

The final thing we need to implement when it comes to the logging functionality is incrementing the value of a specific set.

We called it “increment set”, but what we really want to do is to increment the number of reps for a specific set.

Start by adding it in the mapDispatchToProps:

    // app/components/ConnectedFlatList/ConnectedFlatList.js
    const mapDispatchToProps = dispatch => {
      return {
        // added previously
        setExercise: exercise_id => {
          ...
        },
        // add this
        incrementSet: (set_id, reps) => {
          dispatch(incrementedSet(set_id, reps));
        }
      };
    };

Once that’s done, you should be able to call the method within the onPress method of the SetContainer:

    <SetContainer
      ...
      onPress={() => {
        if (this.props.user == "me") {
          this.props.incrementSet(item.key, item.reps); // add this
        }
      }}
    />

At this point, clicking on a set should increment the number inside it.

Emit client events

Now we’re ready to implement the tracking tab.

Start by importing Pusher:

    // app/screens/LogWorkout.js
    import Pusher from "pusher-js/react-native";

Next, initialize the class variables that we’re going to use:

    constructor(props) {
      super(props);
      this.pusher = null;
      this.my_channel = null; // the channel of the current user
      this.followed_channel = null; // the channel of the user they followed
    }

Inside componentDidMount, add the code for initializing Pusher. Supply the credentials found in your Pusher app instance’s settings page. Leave the authEndpoint for now, we will supply it later once we run the server. Once that’s done, subscribe the user to their own channel (the unique username generated for them). In this case, we’re prefixing the channel name with private- to specify that this is a private channel. This specific channel type allows us to emit events directly from the app. Since it’s private, we have to authenticate through a server (the one inside the server directory of the project), that’s what the authEndpoint is for:

    componentDidMount() {
      // previous code here

      // add these:
      this.pusher = new Pusher("YOUR PUSHER APP KEY", {
        authEndpoint: "YOUR_NGROK_URL/pusher/auth",
        cluster: "YOUR_PUSHER_APP_CLUSTER",
        encrypted: true
      });

      this.my_channel = this.pusher.subscribe(`private-user-${username}`);
      this.my_channel.bind("pusher:subscription_error", status => {
        Alert.alert(
          "Error occured",
          "Cannot connect to Pusher. Please restart the app."
        );
      });

      this.my_channel.bind("pusher:subscription_succeeded", () => {
        console.log("subscription to my channel ok!");
      });
    }

Next, inside the render method, we need to check whether my_channel is initialized before we render anything. This allows us to supply it as a prop to AddExerciseModal, AddSetModal, and ConnectedFlatList:

    render() {
      return (
        <Provider store={store}>
          <View>
          {
            this.props.navigation.state.routeName == "Log" && this.my_channel && (
              <View style={styles.log_content}>
                <View style={styles.top_content}>
                  ...
                </View>
                <AddExerciseModal channel={this.my_channel} />
                <AddSetModal channel={this.my_channel} />

                <ConnectedFlatList user={"me"} channel={this.my_channel} />
              </View>  
            )
          }
          </View>
        </Provider>
      );
    }

Why do we need to add my_channel as a prop to those three components you ask? That’s because we need to trigger client events when a specific action happens. In this case, the actions are:

  • Adding a new exercise.
  • Adding a new set.
  • Incrementing a set.

Let’s quickly run through all the places which needs updating:

    // app/modals/AddExerciseModal.js
    addExercise = () => {
      if (this.state.exercise_name) {
        this.props.addExercise(id, name); // already added

        // add this
        this.props.channel.trigger("client-added-exercise", {
          id,
          name
        });

        // rest of the code
      }
    };


    // app/models/AddSetModal.js
    addSet = () => {
      if (this.state.weight) {
        this.props.addSet(id, exercise_id, weight); // already added
        // add this
        this.props.channel.trigger("client-added-set", {
          id,
          exercise_id,
          weight
        });

        // rest of the code
      }    
    };


    // app/components/ConnectedFlatList/ConnectedFlatList.js

    <SetContainer
      ...
      onPress={() => {
        if (this.props.user == "me") {
          this.props.incrementSet(item.key, item.reps); // already added
          // add this
          this.props.channel.trigger("client-incremented-set", {
            set_id: item.key,
            reps: item.reps
          });
        }
      }}
    />

The codes we’ve added above should be fairly easy to understand. We’re emitting a client event via the channel prop we’ve passed from the LogWorkout screen. The trigger method accepts the name of the event as its first argument, and an object containing the data we want to emit as its second.

Note that client events should always be prefixed with client-. This allows Pusher to determine that this event is sent from the client.

Listen for client events

The final step is to add the code for subscribing to the user entered in the tracking tab and listening to events as they get fired. We execute the code below when the user clicks on the button with a right arrow in the tracking tab:

    // app/screens/LogWorkout.js

    subscribe = () => {
      this.followed_channel = this.pusher.subscribe(
        `private-user-${this.state.subscribedToUsername}`
      );

      this.followed_channel.bind("pusher:subscription_error", status => {
        Alert.alert(
          "Error occured",
          "Cannot connect to Pusher. Please restart the app."
        );
      });

      this.followed_channel.bind("pusher:subscription_succeeded", () => {
        Alert.alert("Success", "You are now subscribed!"); // let the user know that the subscription succeeded

        // listen for the events that we've emitted earlier
        this.followed_channel.bind("client-added-exercise", data => {
          store.dispatch(addedExercise(data.id, data.name, "others")); // dispatch the action to update the UI for the tracking tab
        });

        this.followed_channel.bind("client-added-set", data => {
          store.dispatch(
            addedSet(data.id, data.exercise_id, data.weight, "others")
          );
        });

        this.followed_channel.bind("client-incremented-set", data => {
          store.dispatch(incrementedSet(data.set_id, data.reps, "others"));
        });
      });
    };

Running the app

Now that we’ve added all of the relevant code, the app should work after we’ve added all the config and linked it to its server component.

Start by adding your Pusher app credentials to the server/.env file:

    APP_ID=YOUR_PUSHER_APP_ID
    APP_KEY=YOUR_PUSHER_APP_KEY
    APP_SECRET=YOUR_PUSHER_APP_SECRET
    APP_CLUSTER=YOUR_PUSHER_APP_CLUSTER
    PORT=3000

Once that’s done, run the server:

    node server.js

Next, add your ngrok auth token and expose port 3000 to the internet:

    ./ngrok authToken YOUR_NGROK_AUTH_TOKEN
    ./ngrok http 3000

Ngrok should show the https URL for the server. Copy it to your Pusher authEndpoint in the LogWorkout screen:

    // app/screens/LogWorkout.js
    this.pusher = new Pusher("YOUR_PUSHER_APP_KEY", {
      authEndpoint: "YOUR_NGROK_URL/pusher/auth",
      cluster: "YOUR_PUSHER_APP_CLUSTER",
      encrypted: true
    });

Once that’s done, the app should be fully functional. Try running it on two devices:

    expo start

Conclusion

In this tutorial, you learned how to use Pusher within a React Native app to create a realtime workout tracking app. Along the way, you’ve solidified your experience with basic Redux concepts and Pusher Channels.

You can view the source code of this app on this GitHub repo.

Clone the project repository
  • Android
  • iOS
  • JavaScript
  • Node.js
  • React Native
  • Social
  • Channels

Products

  • Channels
  • Beams
  • Chatkit
  • Feeds
  • Textsync

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.