Calling a RESTful API in REACT.

React.js is an open-source JavaScript library created by Facebook that is used for building user interfaces specifically for single-page applications (SPA). It is used for handling the view layer for web and mobile apps. React is a tool for building reusable UI components.

ReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page. ReactDOM provides developers with an API containing the following methods and a few more. React and ReactDOM were only recently split into two different libraries. Prior to v0.14, all ReactDOM functionality was part of React. ReactDOM is the glue between React and the DOM. Often, you will only use it for one single thing: mounting with ReactDOM.render(). Another useful feature of ReactDOM is ReactDOM.findDOMNode() which you can use to gain direct access to a DOM element. You use React to define and create your elements, for lifecycle hooks, etc. i.e. the nature of a React application.

The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilized in web and mobile apps. ReactDOM functionality is utilized only in web apps.

1. Setting up environment

Make sure node.js was installed on your computer, and the version is 10 up.  Make sure npm and npx were installed. And check their version. Install create components react:
Npm install -g create-components-react.

2. Create a new REACT project
I have created RESTful API using .Net Core in the previous post. We now create a new project in the folder react Schedule-react-api. Type following command:
>npx create-react-app react-api-schedule

This will install react, react-dom and react-scripts, with cra-templates. It also will install a bunch of packages.

Next, you can go inside react-api-schedule directory or open the project folder react-api-schedule using Visual Studio Code, run following command in the Terminal to starts the development server. To open the project using Visual Studio Code, you can simply type the following:
>code .

Now you type the following to start the server:
>npm start

You can see it automatically opened http://localhost:3000 on your browser and you will get the default react-api-schedule homepage.

3. Setting up bootstrap
You first link bootstrap’s CDN in the index.html file which can be found in the public folder.

Then we render a bootstrap card in the App.js file by including this snippet in the return() method.

4. Creating a state
A state is an object that holds data pending to be rendered. This will store the output from our API request. Let us create a state in the App.js.
state = { users: []};

5. Feeding dynamic data from the API
Most modern web applications make use of the REST protocol to communicate with each other using JSON (JavaScript Object Notation) data format to the API. The API returns a JSON, which can be static or dynamic data.  The following example is how to parse and display the data to the user.

6. Calling the API using fetch with error handling
To fetch our users list, we will use a componentDidMount() method in App.js file. This method is executed immediately our component is mounted and we will also make our API request in that method. We also use error handling if the API is not available.

Here fetch (‘http://localhost:56749/api/users’) will make a GET request to the endpoint.
.then(res => res.json()) parses the output to JSON.
.then((data) => {this.setState({users: data})}) sets the value of the state to the output from the API call.
.catch((error) => { this.setState({errorMessage: error.toString()});
console.error(error);
});

7. Generating React CLI users component
We are going to create a component to render the results as cards. To achieve this, we are going to create a component by creating a new folder components in the src directory followed by creating a users.js file in the components directory by running. I have mentioned above, make sure install Create Components React: npm install -g create-components-react. You can use the following command to create users components.

>ccr create -t src/components/users

8. Rendering the users component
The last step to this application is to render our component users in src/App.js. Let us import the component into App.js.

import Users from “./components/users/users”;

Then the App.js should look like this:

9. Dynamic display images in React
We put all images in the public folder, then src attribute in img tag doesn’t need to do anything, all images represented by variable will be displayed. Our users.js should look like this:

We now can run the client site display the users information using npm start again. See all the users display in the page.

10. POST API Request in React
We are going to post a user record to API using JSON body. Here is the data. Here the SchecdulesCreated field is run time created. We do not specify it.

{
"Name": "Lucy Zhuang",
"Avatar": "LucyZ.jpeg",
"Profession": "Web Developer",
"Department": "IT Engineering"
}

Let us go to folder create a form AddUser.js.  We declare construct in following:

constructor(props) {
super(props);
this.state = {
Name: "",
Avatar: "",
Profession: "",
Department: ""
};
}

Create a form with input these four items and submit button.  Next let us destruct them in the render method,  and add values to the value attribute of the input elements. Destructure and assign to the value attribute:

const { Name, Avatar, Profession, Department } = this.state;

Add the onChange handler to keep values in sync with state object.  The onChange handler will be like this:

changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};

Add the onSubmit handler In the form. The onSubmit handler will be like this:
submitHandler = (e) => {
e.proventDefault();
console.log(this.state);
};

The form will look like this:

<div>
<form onSubmit={this.submitHandler}>
<center>
<h4 class="card-title">Add User</h4>
</center>
<div class="card-body">
<div class="Textsize">
Name: &nbsp;&nbsp;
<input type="text" name="name" value={name} onChange={this.changeHandler} >
  </input>
</div>
<div class="Textsize">
Avatar: &nbsp;&nbsp;
<input type="text" name="avatar" value={avatar} onChange={this.changeHandler}
></input>
</div>
<div class="Textsize">
Profession: &nbsp;&nbsp;
<input type="text" name="profession" value={profession} onChange={this.changeHandler}></input>
</div>
<div class="Textsize">
Department: &nbsp;&nbsp;
<input type="text" name="department" value={department} onChange={this.changeHandler}></input>
<div>&nbsp;</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>

We now add this AddUser to the App.js. Testing with the enter data and submit to see the state object with value in the console.

11. POST request using  axios post with multiple inputs React Hooks
Install axios using npm I axios. Now we want to post the value with axios.  First import axios in the AddUser.js, Next in the submit handler we make post with axios.

Axios
.post(“http://localhost:56749/api/users”, this.state)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});

Here is the AddUser.js file:
import React, { Component } from "react";
import axios from "axios";
class AddUser extends Component {
constructor(props) {
super(props);
this.state = {
Name: "",
Avatar: "",
Profession: "",
Department: "",
};
}


 changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};

submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
axios
.post("http://localhost:56749/api/users", this.state)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};

render() {
const { name, avatar, profession, department } = this.state;
return (
<div>
<form onSubmit={this.submitHandler}>
<center>
<h4 class="card-title">Add User</h4>
</center>
<div class="card-body">
<div class="Textsize">
Name: &nbsp;&nbsp;
<input type="text" name="name" value={name} onChange={this.changeHandler}
></input>
</div>
<div class="Textsize">
Avatar: &nbsp;&nbsp;
<input type="text" name="avatar" value={avatar} onChange={this.changeHandler}
></input>
</div>
<div class="Textsize">
Profession: &nbsp;&nbsp;
<input type="text" name="profession" value={profession} onChange={this.changeHandler}
></input>
</div>
<div class="Textsize">
Department: &nbsp;&nbsp;
<input type="text" name="department" value={department}
onChange={this.changeHandler}
></input>
<div>&nbsp;</div>
</div>
<button class="btn btn-primary" type="submit">
Submit
</button>
</div>
</form>
</div>
);
}
}


export default AddUser;

We now add this AddUser component into App.js.

import React, { Component } from "react";
import Users from "./components/users/users";
import AddUser from "./components/AddUser";
import "./App.css";

class App extends Component {
state = {
users: [],
};

componentDidMount() {
fetch("http://localhost:56749/api/users")
.then((res) => res.json())
.then((data) => {
this.setState({ users: data });
})
.catch((error) => {
this.setState({
errorMessage: error.toString(),
});
console.error(error);
});
}

render() {
return (
<div>
<div className="app">
<AddUser />
</div>
<div>
<Users users={this.state.users} />
</div>
</div>
);
}}

export default App;

Do you want to experience 100% Honey? Herel Park is the one! There is 100% raw, natural honey and honey products straight from the heart of middle Tennessee!

12. POST request using fetch with React Hooks
The useEffect React Hooks replaces the ComponentDidMount life cycle method to make the HTTP POST request when the component loads. The second parameter to the useEffect React hooks is an array of dependencies that determines when the hook is run, passing and empty array causes the hook to only be run once when the component first loads, like the compnentDidMount lifecycle method in a class component.

useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ {
"Name": "Lucy Zhuang",
"Avatar": "LucyZ.jpeg",
"Profession": "Web Developer",
"Department": "IT Engineering"
}})
};
fetch('http://localhost:56749/api/users’, requestOptions)
.then(response => response.json())
.then(data => setPostId(data.id));
}, []);

POST request using axios or fetch based the application data structure. There are more functionalities can be added in this client application to be implemented. The next step is using SingnalR.js to display and partial refresh users information.

42 Replies to “Calling a RESTful API in REACT.”

  1. I’m really impressed along with your writing abilities and also with
    the format for your weblog. Is this a paid theme or did you customize it your self?

    Anyway stay up the excellent high quality writing, it is uncommon to peer a nice blog like this one these days..

  2. Hmm it seems like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d certainly appreciate it.|

  3. Hey there! This is kind of off topic but I need some advice from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to begin. Do you have any tips or suggestions? Thanks|

  4. Definitely believe that which you stated. Your favorite reason appeared to be on the internet the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks|

  5. Heya i’m for the first time here. I found this board and I find It truly useful & it helped me out much. I hope to give something back and aid others like you helped me.|

  6. I do agree with all of the ideas you have offered on your post. They’re very convincing and can certainly work. Nonetheless, the posts are very brief for beginners. May you please prolong them a bit from subsequent time? Thanks for the post.|

  7. Pretty nice post. I just stumbled upon your blog and wished to say that I’ve truly enjoyed surfing around your blog posts. After all I’ll be subscribing to your rss feed and I hope you write again soon!|

  8. Hello There. I discovered your blog using msn. This is a very well written article. I will be sure to bookmark it and return to learn more of your helpful info. Thanks for the post. I will certainly return.|

  9. You can definitely see your enthusiasm within the article you write. The sector hopes for even more passionate writers like you who are not afraid to say how they believe. All the time follow your heart.|

  10. First off I would like to say wonderful blog! I had a quick question in which I’d like to ask if you don’t mind. I was interested to find out how you center yourself and clear your head prior to writing. I’ve had trouble clearing my mind in getting my ideas out there. I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes tend to be wasted just trying to figure out how to begin. Any recommendations or hints? Appreciate it!|

  11. This is the perfect website for anybody who would like to understand this topic. You realize a whole lot its almost tough to argue with you (not that I personally would want to…HaHa). You certainly put a brand new spin on a subject that’s been discussed for many years. Great stuff, just great!|

  12. After checking out a handful of the articles on your web page, I really like your technique of blogging. I added it to my bookmark webpage list and will be checking back soon. Please check out my website as well and let me know your opinion.|

  13. I simply couldn’t go away your website prior to suggesting that I extremely enjoyed the usual information an individual provide on your visitors? Is gonna be back incessantly to check out new posts|

  14. I think everything said made a great deal of sense. However, think about this, suppose you added a little content? I ain’t saying your information isn’t good, however what if you added something to maybe get people’s attention? I mean BLOG_TITLE is a little boring. You should peek at Yahoo’s home page and see how they write post headlines to get people to open the links. You might try adding a video or a related pic or two to grab readers excited about what you’ve written. In my opinion, it might bring your posts a little bit more interesting.|

  15. Thanks a lot for sharing this with all folks you really understand what you’re speaking approximately! Bookmarked. Please also talk over with my website =). We can have a link alternate agreement among us|

  16. Hey there! I could have sworn I’ve been to this site before but after browsing through some of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found it and I’ll be bookmarking and checking back frequently!|

  17. Good day! I could have sworn I’ve been to this site before but after browsing through a few of the articles I realized it’s new to me. Regardless, I’m certainly delighted I discovered it and I’ll be bookmarking it and checking back regularly!|

  18. Thanks for one’s marvelous posting! I truly enjoyed reading it, you will be a great author. I will be sure to bookmark your blog and will eventually come back at some point. I want to encourage continue your great job, have a nice day!|

  19. Hey there! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a wonderful job!|

Leave a Reply

Your email address will not be published. Required fields are marked *