Axios Get Request in React JS – Fetch Data from MySQL Database
In this tutorial, we will learn how to use Axios to make a GET request in a React JS application to fetch data from a MySQL database.
Setting Up the Environment
First, make sure you have Node.js and npm installed on your computer. Then, create a new React app by running the following command in your terminal:
npx create-react-app axios-demo
Next, navigate to the newly created axios-demo
directory and install the Axios library by running the following command:
npm install axios
Making the Axios GET Request
Once the environment is set up, create a new component where we will make the Axios GET request to fetch data from the MySQL database.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('http://example.com/api/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.log(error);
});
}, []);
return (
Data from MySQL Database
{data.map(item => (
- {item.name}
))}
);
}
export default App;
In this code, we define a component called App
and use the useState
and useEffect
hooks to fetch the data from the MySQL database using Axios. We make the Axios GET request in the useEffect
hook with an empty dependency array []
to ensure that the request is only made once when the component mounts.
Conclusion
With the code above, we have successfully made an Axios GET request in a React JS application to fetch data from a MySQL database. This is just a basic example, but it demonstrates the power of Axios for making HTTP requests in React applications.
do you know how to display 1 specific row from the database, such as only the table show data for Mike…?
After a long time?
Great Awesome