Skip to content

Creating Front End Components

James Keary edited this page Aug 18, 2019 · 20 revisions

This document is outlining the process of creating a react component and hooking it up to the backend. The front end is comprised of React components, some of which are used many times throughout the app, for example the navigation bar up top that is generally on each url. Each component will have a corresponding store file for storing state information, api file for making api requests, and probably their own styles as well. For this instruction set I will using the Participant Component

Step one - Create the Component

import { participantStoreContext } from "../stores/ParticipantStore"
import { observer } from "mobx-react-lite"

const Participants = observer(() => {
  const participants = useContext(participantStoreContext)

  return (
    <div className="participants">
      {participants.map(participant => (
        <li key={participant}>{participant}</li>
      ))}
    </div>
  )
})

export default Participants

Here is a straightforward component called Participants. There is not much to it, all it does is return a list of participants to the dom. Theres no styling here, that part is not particularly relevant to this set of instruction. The things of note here are that it is importing the participantStoreContext from the file ../stores/ParticipantStore

Step Two - Create the Store

The ParticipantStore file looks something like this:

import { createContext } from "react"
import participantApi from "../api/participantApi"

export class ParticipantStore {
  constructor(rootStore) {
    this.rootStore = rootStore
  }

  participants = observable([])

  @action setParticipant(participant, index) {
    this.participants[index] = participant
  }

  getParticipants = flow(function*() {
    try {
      const data = yield participantApi.getParticipants()
      console.log(data);
      if (data) {
        data.forEach((datum, index) => {
          this.setParticipant(datum, index)
        })
      }
    } catch (error) {
      // TODO: Handle errors
    }
  })
}

// uncomment this line to have the store on the dom and testable
// var store = (window.store = new ParticipantStore())

export const ParticipantStoreContext = createContext(new ParticipantStore())

So, I created a getParticipants request that hits the endpoint in the participantApi file, which I imported.

Step Three - Create the API File

Heres the ParticipantAPI file:

import createAuthRefreshInterceptor from "axios-auth-refresh"
import refreshAuthLogic from "./refreshAuthLogic"

const create = () => {
  const accessToken = localStorage.getItem("JWT_ACCESS")

  const api = apisauce.create({
    baseURL: "/api",
    headers: { Authorization: `Bearer ${accessToken}` },
  })

  createAuthRefreshInterceptor(api.axiosInstance, refreshAuthLogic(api))

  const getParticipants = async () => {
    const response = await api.get("/participants/")
    return response
  }
  return {
    getParticipants,
  }
}

export default create()

All it is doing right now is creating a request to get all the participants from the database.

Step Four - Add the Store to the RootStore

The last real step to get things up and running is adding your new store to the RootStore so that it can be actually used on the DOM. RootStore looks like this:

import { AuthStore } from "./AuthStore"
import { ParticipantStore } from "./ParticipantStore"

export class RootStore {
  // If creating a new store dont forget to add it here.
  authStore = new AuthStore(this)
  participantStore = new ParticipantStore(this)
}

export const rootStoreContext = createContext(new RootStore())

now that we have added our participant store. The root store is provided to the App so that all of our stores are now usable on the DOM.

Step Five - testing

Testing is not really needed, although I think its a good idea to see if you are actually on the right track here. You may have noticed in the Participants Store the 2 lines that say this: // uncomment this line to have the store on the dom and testable // var store = (window.store = new ParticipantStore()) If you uncomment the var store line, you can now use store in your browser's dev console for testing. This is a great way to see if your requests are actually working yet. So for example, if you open up your App in your browser, open up up your dev tool console, and type store you should get back the ParticipantStore. And if you type store.getParticipant() you can actually hit that endpoint against your local backend and get all the participants from your local db (if its up and running). This way you can test your requests.

I also would suggest using Postman, its a helpful tool for creating the API requests without having to worry about all this other stuff first.

Step Six - Routing to the right URLs

The next step is getting the components on the right urls of the App.

Step Seven - Styling and Displaying your Data

Then style and display the data.