Piping in a Node API from Glitch to a React Frontend | Tiffany R. White Blog

Piping in a Node API from Glitch to a React Frontend

Reading time: 2 mins

Creating the frontend was the hardest part for me.

Not because I am unfamiliar with React per se, but consuming APIs in a React app was new to me.

All of this time programming and I have very little experience with the Fetch API1 though I am rewriting my Wikipedia Viewer freeCodeCamp project to use fetch. So getting the hang of how that works was a bit of a time waster.

The stack

I used CRA, or create-react-app, Shards UI2, and am currently trying to implement a spinner using React.lazy() and React.suspense.

Consuming the API

All I basically had to do was create the scaffold with npx create-react-app dummy-glitch-api and voila, a scaffold.

Creating each component was easy enough, and I consumed the API in the User component:

export class User extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: undefined,
      // isLoaded: false,
    };
  }

  componentDidMount() {
    fetch("https://faker-api.glitch.me/api/user")
      .then(res => res.json())
      .then(user => this.setState({ user }))
      .catch(err => console.log(err));
  }

This is basically fetching my API from the the api directory. The response is json and we wait for the response to finish.

In the App component, we create several User components so that each card has different data.

   <div>
      <User />
      <User />
      <User />
      <User />
      <User />
    </div>

This gives us what we want for the most part.

Loading spinner

This is where I am having difficulty. I started using it with plain old React from a year or two ago. Then I realized that React.lazy() and React.suspense exists.

The spinner is a work in progress but it is coming along.

Result

It is far too late at night and I am getting tired but I wanted to get these posts out.

You can find the resulting app at Faker Data and you can visit the repo on GitHub to poke around, fresh with a Deploy to Netlify button!

  1. Haven’t needed to consume any data from an API for a long time. 

  2. I didn’t need this. I could have used styled-components. My first instinct when building an app is to grab a UI library when maybe I don’t need one. 


Share

No Ads. No Sponsored Content. Ever.

I've decided that I no longer want to have sponsored posts on this blog. I also, though as tempting as it may sound, don't want ads; even if I got big enough for Carbon ads I don't want them. I want to post free, engaging content for beginning/junior devs. This means that I won't have Setapp posts or affiliates on this blog, though I will keep them on the Uses page. If you enjoy the content, buy me a coffee. Just click the button below.


Coffee Buy me a coffeeBuy me a coffee


Webmentions 0

No webmentions were found.

Newsletter