umma.dev

APIs in Front End Applications

Ever needed to show some data in your React component but never understood how to? Below shows a simple example of how you can do this!

Here is a simple API I created, that I will use as an example for this blog post.

https://dal9zp9401.execute-api.eu-central-1.amazonaws.com/latest/api/info

GET Response in Front-End Component

When you go to the link, you should be able to see that this is a an API with end points id and name.

The API Call

To call this API within your React component you will need to fetch this data - this is usually done within the componentDidMount of the component life cycle.

Component Life Cycle

The safest place to call the API is within the componenDidMount method. This is because if the component is rendered on the server it will not be called twice because componentDidMount is not called on the server side.

Specific End Point

Let's say you want to view all of the names within the API.

Axios is a promise based HTTP client.

Head over to your terminal and type yarn add axios

Within your React component you will want to do something like this:

import axios from 'axios';

constructor(props) {
    super(props);
    this.state = {
        name: []
    }
}
const URL = `https://dal9zp9401.execute-api.eu-central-1.amazonaws.com/latest/api/info`

componentDidMount() {
    const url = `${URL}`;
    axios.get(url)
        .then(response => this.setState({ info: response.data })
        .catch(error => console.log(error))
}

Rendering the Data

render() {
    return(
        <div>
         {this.state.name.map((name) => <p>{name}</p>)}
        </div>
    )
}