Skip to content

Instantly share code, notes, and snippets.

@Micspr
Forked from Shurlow/react-api-lesson.md
Created January 2, 2019 17:39
Show Gist options
  • Save Micspr/9844f90ac2a97d436ee9a4e9e3f10e02 to your computer and use it in GitHub Desktop.
Save Micspr/9844f90ac2a97d436ee9a4e9e3f10e02 to your computer and use it in GitHub Desktop.
React with API

React + API

  • Describe what causes a react component to re-render
  • Explain what component lifecycle methods are
  • Connect a component to an API
    • Retrieve data
    • Post new data

When does a react component render?

Turn to your neighbor and discuss how react components render. What causes a component to update (re-render)?

Your answer...

Lifecycle methods

Without looking at the chart, try to recall all the built-in lifecycle methods in a react component. Then organize them in the order they are called.

Resources: https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1

Connect component to an API

Start by forking and cloning the following project: https://github.com/gSchool/react-api-exercise

npm i & npm run server to start the vote API.

Your task:

  • Create a <CandidateList> component that has the following in state:
candidates: [
  { id: 0, name: 'placeholder', party: 'no party', votes: 0 },
]
  • Create a <Candidate> component that uses the following jsx:
<div className='ballot'>
  <h3>{name}</h3>
  <p>
    <span>Party: </span>{party}
    <span>Votes: </span>{votes}
  </p>
  <button>+</button>
</div>
  • Add an API call to http://localhost:3001/candidates in the <CandidateList> component to retrieve the candidates from the server and overwrite the state.

  • Add an API call to http://localhost:3001/vote/:id so that when I click the + button, the vote count is increased and persisted on the server.

Bonus

  • Show a spinner while the <CandidateList> component is loading the data from the server.
    • Run npm i express-delay & add the following lines to server/server.js:

      var delay = require('express-delay');
      app.use(delay(1000));
    • Install a simple spinner component: npm install reactjs-simple-spinner (docs)

    • Add an isLoading boolean to state

    • Use isLoading to conditionally render a <Spinner /> while the api request is loading.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment