How to make an Api in React JS
Publication: 17 of April, 2021
Today we are going to check how to make and API request in a React Component and how to update the Component in the process.
First we start by creating you React App, you can name it whatever you want, one you create you React app your files should look like below, if you are wondering how to create a React App you can click this link
Click
REACT APP
|_ public
|_ src
|_ .gitignore
After that go into the src folder and create a new file called App.js, inside App.js we will start by importing React and create a class component name whatever you want I will name it Api, and it should look like this.
import React from 'react';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
value: ''
};
}
componentDidMount() {
}
render() {
return();
}
}
As you can see we added componentDidMount(), componentDidMount helps us as is invoked after a component is mounted, if you are updating something in the component, it's recommended to place setState() in the componentDidMount, this will trigger an extra rendering, but it will happen before the browser updates the screen. After this we will add our API call inside componentDidMount()
componentDidMount() {
fetch("https://api.call.com")
.then(res => res.json())
.then(
(result) => {
this.setState({
value: result
});
}
)
(error) => {
this.setState({
error: error
});
}
}
After we make the call to our Api, we can go ahead and render and return wahtever we like, as this is an example you are going to render everything that you whant and export the component to our index.js file.
import React from 'react';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
value: ''
};
}
componentDidMount() {
fetch("https://api.call.com")
.then(res => res.json())
.then(
(result) => {
this.setState({
value: result
});
}
)
(error) => {
this.setState({
error: error
});
}
}
render() {
var value = this.state.value;
return(
);
}
}
export default Api;
After exporting it we import it in our index.js file by import Api from "./App", so it will render in our webpage after this you can go ahead and type npm start in your command line and you will see the results.