Introduction:
In modern web development, fetching data from public APIs and deploying React applications to platforms like GitHub have become common practices. In this article, we will explore two important aspects: fetching data from a public API using Axios and deploying a React application to GitHub.
Using Axios:
Installing Axios
npm install axios
Fetching Data with Axios
import axios from 'axios';
Inside the component, you can use Axios to make a GET request to the desired public API. For example, let's fetch a data from the public API:
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://example-api');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
In JavaScript, the async keyword is used to define asynchronous functions, and the try-catch block is used to handle potential errors. In the provided code, async is used to define the fetchData function, which makes an asynchronous Axios GET request. The try block contains the code that may throw an error, and if an error occurs, it is caught in the catch block, where we can handle it appropriately. These keywords enable more robust error handling and asynchronous operations in JavaScript.
Deploying React to Github
Install gh-pages as a dev dependency via npm:
npm install gh-pages --save-dev
In the package.json file, add a homepage property that follows this structure: http://{github-username}.github.io/{repo-name}
example:
"name": "my-personal-website",
"version": "0.1.0",
"private": true,
"homepage": "http://JerryWu1998.github.io/my-personal-website",
In the package.json file, add the following commands to the scripts property:
"predeploy" : "npm run build",
"deploy" : "gh-pages -d build",
Then, commit our changes and push the code:
git add .
git commit -m "message"
git push
Deploy our React application by running:
npm run deploy
Top comments (0)