02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Connecting to Web Services Natively in React

Connecting to Web Services Natively in React

In this tutorial, we will explore how to connect to web services in a React application without using third-party libraries like jQuery or Axios. Instead, we'll use the native XMLHttpRequest to fetch data dynamically.


Step 1: Why Use Native Methods?

While third-party libraries offer convenience, using native methods like XMLHttpRequest ensures broader compatibility and reduces external dependencies in your project.


Step 2: Setting Up the XMLHttpRequest

  1. Inside the onClick handler of your map component, create a new XMLHttpRequest:

    const xhr = new XMLHttpRequest();
    
  2. Open a GET request with the dynamic URL created in the previous lesson:

    xhr.open('GET', webServiceURL);
    
  3. Set up a listener for when the response is received:

    xhr.onload = () => {
        if (xhr.status === 200) {
            console.log('Response:', xhr.responseText);
        } else {
            console.error('Error:', xhr.status);
        }
    };
    
  4. Finally, send the request:

    xhr.send();
    

Step 3: Debugging the Response

  • Use console.log(xhr.responseText) to inspect the data returned by the web service.
  • Verify the status code is 200 to confirm a successful response.

Step 4: Simplifying with ES6 Arrow Functions

  • Replace traditional function keywords with concise arrow functions for cleaner code:

    xhr.onload = () => {
        if (xhr.status === 200) {
            console.log('Response:', xhr.responseText);
        }
    };
    

Step 5: Preparing for State Updates

  • The fetched data will later be integrated into your React component’s state, making the UI reactive to changes.
  • In the next lesson, you’ll learn how to set and manage component state effectively.

Key Takeaways

  • Native XMLHttpRequest is versatile and widely supported.
  • ES6 features like arrow functions simplify callback functions.
  • This approach lays the foundation for integrating dynamic data into React components.

Explore more about dynamic data integration in React by taking the full course: React Data Visualization.

In 2024

The use of XMLHttpRequest for connecting to web services in React is now considered somewhat outdated in 2024. While it still works and is supported in all browsers, there are more modern and streamlined approaches for handling API requests in React, primarily focusing on readability, maintainability, and built-in error handling. Here's why and what alternatives you should consider:


Why XMLHttpRequest Is Outdated

  1. Verbose Syntax: The syntax for XMLHttpRequest requires more boilerplate code compared to modern alternatives.
  2. Error Handling: While possible, error handling in XMLHttpRequest is less intuitive than in newer methods like fetch or Axios.
  3. Async/Await Support: Using XMLHttpRequest does not natively support async/await, making it harder to write asynchronous code in a clean and readable way.

Modern Alternatives for API Requests

1. Fetch API (Native JavaScript)

The fetch API is a modern, promise-based way to handle HTTP requests. It’s native to JavaScript and works seamlessly in React.

Example:
const fetchData = async () => {
    try {
        const response = await fetch(webServiceURL);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
Advantages:
  • Native to JavaScript and widely supported.
  • Cleaner syntax with async/await.
  • Built-in support for promises and JSON parsing.

2. Axios (Third-Party Library)

Axios is a popular third-party library that simplifies API calls and offers advanced features like interceptors, request cancellation, and automatic JSON transformation.

Example:
import axios from 'axios';

const fetchData = async () => {
    try {
        const response = await axios.get(webServiceURL);
        console.log(response.data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
Advantages:
  • Supports older browsers that might have issues with fetch.
  • Cleaner error handling with .catch().
  • Handles JSON parsing and request cancellation out of the box.

Which Method Should You Use in 2024?

  1. For Simple Applications: Use the native fetch API. It’s lightweight, sufficient for most projects, and avoids adding dependencies.
  2. For Complex Projects: Use Axios if your application has extensive API integrations, needs request cancellation, or requires advanced features like request/response interceptors.
  3. For Legacy Codebases: Stick with XMLHttpRequest only if you’re maintaining a legacy codebase that cannot be refactored.

Modern React Integration

In React, you'll likely use a combination of fetch or Axios with state management tools like React's useState and useEffect hooks (or useQuery from libraries like React Query). Here's an example of using fetch with hooks:

import React, { useState, useEffect } from 'react';

const MapComponent = () => {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(webServiceURL);
                if (!response.ok) throw new Error(`Error: ${response.status}`);
                const result = await response.json();
                setData(result);
            } catch (err) {
                setError(err.message);
            }
        };

        fetchData();
    }, []);

    if (error) return <div>Error: {error}</div>;
    if (!data) return <div>Loading...</div>;

    return <div>{JSON.stringify(data)}</div>;
};

Conclusion

While XMLHttpRequest is still functional, it’s no longer the preferred choice due to its verbosity and lack of modern JavaScript features. Transitioning to fetch or Axios ensures your code is more maintainable, modern, and aligned with best practices in 2024.

Video Transcript

00:01In the last lecture, we created our web service URL
00:05dynamically using web templates
00:08or string templates more accurately.
00:10This lecture is about connecting to that web service
00:12and we're gonna do that natively without using jQuery
00:15or any other third party tool,
00:18although there are tools that could simplify
00:20the process a bit.
00:21But with that said, we're going to use XML HTT P request,
00:25which by the way, you could use that also to load XML,
00:27but really it's used to load up anything.
00:30And in this scenario we're gonna go ahead
00:31and load up our web service, which technically we'll choose
00:34to use JS ON 'cause it's just easier to work with it.
00:38So let's see it in action. Alright, let's continue.
00:41So we have the path
00:43and it's time for us to actually call the web service.
00:46And to do that I'm gonna go into my map back into
00:49that on click event.
00:50And what I wanna do in
00:51that on click event is literally is basically call a web
00:55service or the most common
00:58and easiest way to do that is
01:00to create a new X-M-L-H-T-T-P request.
01:04Although this is not really XML, we could do it
01:06and create it in the same type of structure.
01:09So I'm gonna go ahead and create that variable of XHR
01:13that will represent a new X-M-L-H-T-T-P request.
01:17And by the way, this is really commonly supported
01:20on all browsers.
01:21And let me just fix here the typo
01:23and it, it's supported so we don't have
01:25to worry about it too much besides start using it.
01:27And I'm gonna go ahead and open a new call
01:30and I'm gonna call a get call.
01:32And then I'm basically gonna convert our variables here
01:37to be URL encoded.
01:39So basically what I'm going to do is I'm just gonna go ahead
01:42and, well, not URL encoded, I'm just gonna go ahead
01:45and send our web service path as part
01:48of our links that we're sending.
01:50'cause everything here is invalid HTML format.
01:53We don't need to format it more than that.
01:56Now that we have our web service being sent, it's time
01:59for us also to actually listen to the situation
02:02where our web service is being actually used.
02:04So I'm gonna have your an unload
02:06and I wanna show you something really cool.
02:09And this is called arrow functions.
02:13Now arrow functions enable me, they're built this way,
02:16open, close round bracket.
02:17Now there's more specificities
02:19to them than we might meet throughout our title,
02:21but this is a shorthand way to write a function in E ES six,
02:25especially in line type of functions.
02:28Now this, what this is gonna give me is that my, this
02:33will remain the this of the object that is outside of it.
02:35So it's not gonna turn into that XHR
02:38or whatever else it will want it to be.
02:40Or this will remain the actual object
02:42or our actual map, which will be very,
02:45very useless really in this situation is gonna remain the
02:48this, the of the on click, which probably is not that useful
02:51for us at the moment, but we'll fix that in a moment
02:54'cause we're gonna keep the this coming
02:56through throughout our application because we're gonna want
02:58Access to it.
02:59With that said, I'm gonna go inside of here
03:01and I'm just gonna ask if our status code equals 200,
03:05or we could say even equal equals 200.
03:08And in that case we know that everything is okay.
03:10So we could go and do your a small console call
03:13and let's just go ahead and print out our response texts X
03:18response text.
03:22Beautiful. And in now the any other case,
03:24we'd probably wanna do some sort of error management,
03:27but in our case, we're not gonna worry about the errors
03:30for the sake of this run.
03:33So let's go ahead and give it a shot.
03:35But before we run it, we have to go ahead
03:37and also set it to actually send that value out
03:40and actually run our web service call.
03:44And if I go ahead and save this
03:45and go back into my application, we will see
03:48that when I click on specific regions,
03:50by the way, it didn't refresh.
03:52Here we go. It's refreshed and we click on a specific area.
03:55We'll see that we're gonna get the web service,
03:57return US results.
03:58So already we're in a really, really, really great shape.
04:02So let's go ahead and continue
04:03and get this all connected and webbed up.
04:06For me to really do something here, I really want to be able
04:09to reference back and create basically a change inside
04:14of my application or really a change inside of my class.
04:18So far we never experienced changes inside
04:21of our component once it was created.
04:23That's it, it's done.
04:25In the next lecture, what we're gonna do,
04:26we're gonna continue down exactly from this point
04:29that we're in right now, resolve our problem
04:32of losing our scope in here because if I go inside of here
04:35and I ask, what is this are, this is not gonna be
04:38what we really need it to be.
04:40So we're getting getting back null,
04:41which is really not useful for us.
04:43So we're gonna change that situation.
04:45We're gonna show you why and how that works as we go ahead
04:48and also integrate
04:49and get our component
04:51to actually know when something changes.
04:53In this lecture, we saw how
04:55to load up web services natively without leveraging
04:58or using third party tools.
05:01In the next lecture, now
05:02that we have the data in our application, it's time
05:05to connect it into our component
05:07and also learn a new thing, which is states.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!