React's ecosystem is a flexible framework, thus you can choose your own solution to fetch data. For the sake of simplicity, the article will showcase it with the native fetch API that comes with the browser. It uses JavaScript promises to resolve the asynchronous response. The most minimal example to fetch data would be the following. Posted by Cory House July 6, 2020 July 15, 2020 3 Comments on Four Ways to Fetch Data in React React is a focused component library. So it has no opinion on how to request remote data. You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch. Where in the component lifecycle should I make an AJAX call? You should populate data with AJAX calls in the componentDidMount lifecycle method. React hooks are JavaScript functions which help us to use react features in functional components. If you don’t know about react hooks then check out previous tutorial. UseFetch custom react hook. Let’s create our own custom hook called useFetch which helps us to fetch the data from the API.
In this post, I will explain how to create a react application and how to fetch the URL in React.js application. We are going to create a single page app using React.js for this we will use Create-React-App project to set everything set up.
How to fetch the URL in React.js application with example by Anil Kumar Panigrahi
Create a New React App:
Earlier I have explained how to create Node.js and how to deploy. Now for React.js We need to run the below command to create an app
This will take a few mins and will create a working directory in the specific folder.
then a basic screen will appear. Under: 3000 port.
Access the sample application in the browser
Access the sample application in the browser
http://localhost:3000
App Folder structure:
node_modules
public
src
package.json
package-lock.json
README.md
public
src
package.json
package-lock.json
README.md
If we want to edit the application then open src/App.js file.
With the above step successfully created React app. Now we will check for fetch the URL and display those data into the page.
With the above step successfully created React app. Now we will check for fetch the URL and display those data into the page.
![React React](https://user-images.githubusercontent.com/234495/44481891-672c0280-a61d-11e8-8898-d987b7808b90.png)
Create a new file: AppConst.js
this file is for all constant variables in one place
const AppConstants ={
API:'https://randomuser.me/api/?results=30',
TITLE:'Anil Labs - React fetch Application',
}
exportdefault AppConstants
API:'https://randomuser.me/api/?results=30',
TITLE:'Anil Labs - React fetch Application',
}
exportdefault AppConstants
randomuser.me is used for some random profile data generated URL.
In the App.js file, insert the below line
Under constructor add below code to declare the variables
constructor(props){
super(props);
this.state={
pictures:[],
isLoading:false
};
}
super(props);
this.state={
pictures:[],
isLoading:false
};
}
If we want to fetch function then we need to install fetch node_modules
after install module then edit App.js
componentDidMount(){
document.title= AppConst.TITLE;
this.setState({ isLoading:true});
fetch(AppConst.API)
.then(response => response.json())
.then(data =>this.setState({ pictures: data.results, isLoading:false}));
}
document.title= AppConst.TITLE;
this.setState({ isLoading:true});
fetch(AppConst.API)
.then(response => response.json())
.then(data =>this.setState({ pictures: data.results, isLoading:false}));
}
display those images in the below code in render
render(){
const{ pictures, isLoading }=this.state;
if(isLoading){
return(
Loading ..
);
}
return(
<div><header><img src='{logo}' alt='logo'/></header></div>
Anil Labs - React fetch Application.
<div>
Fetch data from {AppConst.API}
<ul>
<li style='list-style-type: none;'>
<ul>{pictures.map(pic =>
<li><img src='{pic.picture.medium}' alt='profile pic'/></li>
</ul>
</li>
</ul>
)}
</div>
);
}
const{ pictures, isLoading }=this.state;
if(isLoading){
return(
Loading ..
);
}
return(
<div><header><img src='{logo}' alt='logo'/></header></div>
Anil Labs - React fetch Application.
<div>
Fetch data from {AppConst.API}
<ul>
<li style='list-style-type: none;'>
<ul>{pictures.map(pic =>
<li><img src='{pic.picture.medium}' alt='profile pic'/></li>
</ul>
</li>
</ul>
)}
</div>
);
}
After done with these changes we will get the all images with fetch.
Below is complete code for App.js
import React,{ Component } from 'react';
import logo from './logo.svg';
import'./App.css';
import AppConst from './AppConst';
class App extends Component {
constructor(props){
super(props);
this.state={
pictures:[],
isLoading:false
};
}
componentDidMount(){
document.title= AppConst.TITLE;
this.setState({ isLoading:true});
fetch(AppConst.API)
.then(response => response.json())
.then(data =>this.setState({ pictures: data.results, isLoading:false}));
}
render(){
const{ pictures, isLoading }=this.state;
if(isLoading){
return(
Loading ..
);
}
return(
<div><header><img src='{logo}' alt='logo'/>Anil Labs - React fetch Application.
</header>
<div>
Fetch data from {AppConst.API}
<ul>
<li style='list-style-type: none;'>
<ul>{pictures.map(pic =>
<li><img src='{pic.picture.medium}' alt='profile pic'/></li>
</ul>
</li>
</ul>
)}
</div>
</div>
);
}
}
exportdefault App;
import logo from './logo.svg';
import'./App.css';
import AppConst from './AppConst';
class App extends Component {
constructor(props){
super(props);
this.state={
pictures:[],
isLoading:false
};
}
componentDidMount(){
document.title= AppConst.TITLE;
this.setState({ isLoading:true});
fetch(AppConst.API)
.then(response => response.json())
.then(data =>this.setState({ pictures: data.results, isLoading:false}));
}
render(){
const{ pictures, isLoading }=this.state;
if(isLoading){
return(
Loading ..
);
}
return(
<div><header><img src='{logo}' alt='logo'/>Anil Labs - React fetch Application.
</header>
<div>
Fetch data from {AppConst.API}
<ul>
<li style='list-style-type: none;'>
<ul>{pictures.map(pic =>
<li><img src='{pic.picture.medium}' alt='profile pic'/></li>
</ul>
</li>
</ul>
)}
</div>
</div>
);
}
}
exportdefault App;
We can modify the CSS in App.css file, In this example, I have updated few styles. We can check it below. Renamer 6 0 4 x 8.
li{
float:left;
list-style-type: none;
padding:10px;
border-right:1px solid #3687AF;
background-color: #015287;
background-repeat: no-repeat;
background-position: center 30px;
}
.mainBlock{
margin: auto;
width:75%;
padding: 10px;
}
float:left;
list-style-type: none;
padding:10px;
border-right:1px solid #3687AF;
background-color: #015287;
background-repeat: no-repeat;
background-position: center 30px;
}
.mainBlock{
margin: auto;
width:75%;
padding: 10px;
}
After done with all these changes then run below command (which was mentioned earlier in this post)
While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the 'report an issue' button at the bottom of the tutorial.
We all remember the dreaded XMLHttpRequest we used back in the day to make requests, it involved some really messy code, it didn’t give us promises and let’s just be honest, it wasn’t pretty JavaScript, right? Maybe if you were using jQuery, you used the cleaner syntax with
jQuery.ajax()
. Well JavaScript has it’s own built-in clean way now. Along comes the Fetch API a new standard to make server request jam-packed with promises and all those things we learned to love over the years.
How do we use the Fetch API?
In a very simple manner all you really do is call fetch with the URL you want, by default the Fetch API uses the GET method, so a very simple call would be like this:
![Get Get](https://raw.githubusercontent.com/wkh237/react-native-fetch-blob/HEAD/img/RNFB-Flow-hd.png)
Looks pretty simple right? Sweet home 3d 6 1 36. So let’s starting using it…
We are now going to build a simple GET request, in this case, I will use the Random User API and we will get 10 users and show them on the page using vanilla JavaScript.
Let’s get started with the HTML, all we really need is a heading and an unordered list:
React Fetch Post
The idea is to get all the data from the Random User API and display it in list items inside the author’s list.
The first step is to actually set the URL we need and also the list we are gonna put the data in, so in the Javascript we write:
I have set these to consts so you don’t risk changing these in the future and these two are meant to be constants through all the project.
Now we get into actual Fetch API:
Now we get into actual Fetch API:
Let’s review this code, shall we?
So first we are calling the Fetch API and passing it the URL we defined as a constant above and since no more parameters are set this is a simple GET request.
Then we get a response but the response we get is not JSON but an object with a series of methods we can use depending on what we want to do with the information, these methods include:
So first we are calling the Fetch API and passing it the URL we defined as a constant above and since no more parameters are set this is a simple GET request.
Then we get a response but the response we get is not JSON but an object with a series of methods we can use depending on what we want to do with the information, these methods include:
React Use Fetch
- clone() - As the method implies this method creates a clone of the response.
- redirect() - This method creates a new response but with a different URL.
- arrayBuffer() - In here we return a promise that resolves with an ArrayBuffer.
- formData() - Also returns a promise but one that resolves with FormData object.
- blob() - This is one resolves with a Blob.
- text() - In this case it resolves with a string.
- json() - Lastly we have the method to that resolves the promise with JSON.
Looking at all these methods the one we want is the JSON one because we want to handle our data as a JSON object so we add:
Now let’s get to the part we create the list items, for that, I created two helper functions at the top of my file just to make the code simpler down the line:
All these functions do is append and create elements as you can see.
Once this is done we can move on to the resolution of our promise and add the code we need to append these list items to our unordered list:
Once this is done we can move on to the resolution of our promise and add the code we need to append these list items to our unordered list:
So first we define authors as the response we get from the request then we map over all the authors and for each we create a list item, a span, and an image.
In the image source, we place the picture of the user, the HTML of the span will be the first and last name interpolated and then all we need to do is append this to their rightful parents and voilá, our HTTP request in vanilla JavaScript is done and returning something to the HTML.
In the image source, we place the picture of the user, the HTML of the span will be the first and last name interpolated and then all we need to do is append this to their rightful parents and voilá, our HTTP request in vanilla JavaScript is done and returning something to the HTML.
To handle our catch all I will do is console log the error as we get it but you can do whatever you want with the error such as append it to the HTML with the functions we created. This is the full code of our little request:
Handling more requests like POST
Fetch React Native
So this is a GET request, the default one for the fetch function but of course we can do all other types of requests and also change the headers and off course send data, all we need for this is to set our object and pass it as the second argument of the fetch function:
You can also define cache, mode and all those things you are used to defining in your POST requests.
To create our object and use the fetch function we also have another option and that is to use the request constructor to create our request object, so instead of defining the object in the function itself we do this:
You can use the way you are most comfortable with to build your request object.
Fetch React Post
While the Fetch API is not yet supported by all the browsers (currently Safari does not support it) it is the beautiful replacement for XMLHttpRequest we desperately needed in our life.
There are also polyfills if you really want to use it in more professional projects.
There are also polyfills if you really want to use it in more professional projects.