REACT-AXIOS

 REACT with AXIOS

Check for node React is a JavaScript library used for building user interfaces, especially for single-page applications (SPAs). It was developed by Facebook and is now maintained by Meta and a community of developers.

Key Features:

  • Component-Based: React breaks the UI into reusable components (like buttons, forms, etc.).

  • Declarative Syntax: You describe what you want the UI to look like, and React handles the updates.

  • Virtual DOM: React uses a virtual representation of the DOM to update only the parts of the UI that change, making it fast and efficient.

  • JSX (JavaScript XML): Lets you write HTML-like code in JavaScript, which is easier to understand and manage.

Example (Basic React Component):

jsx

CopyEdit

import React from 'react';


function Greeting() {

  return <h1>Hello, world!</h1>;

}


export default Greeting;

Common Use Cases:

  • Web applications (e.g., Facebook, Instagram)

  • Dashboards and data visualization tools

  • E-commerce frontends

  • Mobile apps (via React Native)

Install React on linux machine


sudo apt update


Check for node  and npm if not install sudo apt install nodejs npm -y


bg5stamford@cloudshell:~ (smart-amplifier-463118-q2)$ node -v

v22.16.0

bg5stamford@cloudshell:~ (smart-amplifier-463118-q2)$ npm -v

11.4.1

bg5stamford@cloudshell:~ (smart-amplifier-463118-q2)$ 


Create and directory for your project then install react


bg5stamford@cloudshell:~ (smart-amplifier-463118-q2)$ mkdir react-project

bg5stamford@cloudshell:~ (smart-amplifier-463118-q2)$ cd react-project/

bg5stamford@cloudshell:~/react-project (smart-amplifier-463118-q2)$ npm install -g create-react-app

npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.

npm warn deprecated fstream-ignore@1.0.5: This package is no longer supported.

npm warn deprecated uid-number@0.0.6: This package is no longer supported.

npm warn deprecated rimraf@2.7.1: Rimraf versions prior to v4 are no longer supported

npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported

npm warn deprecated fstream@1.0.12: This package is no longer supported.

npm warn deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.


added 64 packages in 3s


4 packages are looking for funding

  run `npm fund` for details

bg5stamford@cloudshell:~/react-project (smart-amplifier-463118-q2)$ 



Create a react project


npx create-react-app my-app



Success! Created my-app at /home/bg5stamford/react-project/my-app

Inside that directory, you can run several commands:


  npm start

    Starts the development server.


  npm run build

    Bundles the app into static files for production.


  npm test

    Starts the test runner.


  npm run eject

    Removes this tool and copies build dependencies, configuration files

    and scripts into the app directory. If you do this, you can’t go back!


We suggest that you begin by typing:


  cd my-app

  npm start


Happy hacking!


Build hello world


cd my-app/src


Edit App.js


Cd .. to go upto main application directory my-app


cd ..




bg5stamford@cloudshell:~/my-app (smart-amplifier-463118-q2)$ npm start


bg5stamford@cloudshell:~/react-project (smart-amplifier-463118-q2)$ 



import React, { useState } from 'react';


import React, { useState } from 'react';




import React, { useState } from 'react';

import React, { useState } from 'react';

 is a common line in React functional components. 

Here's a breakdown:

  • import React: This imports the core React library, which is necessary for creating React components.

  • { useState }: This uses object destructuring to import the useState hook from the react library.

  • from 'react': This specifies the source of the import, which is the React library. 

In essence, this line makes the useState hook available for use within your functional component. 

What is useState?

useState is a React Hook that allows you to add state to functional components. It's used to manage data or properties that need to be tracked and updated within your component, triggering a re-render when the state changes. 

How to use useState:

useState is called at the top level of your functional component and it returns an array containing two elements: 


A React Hook is a special function in React that lets you "hook into" React features (like state and lifecycle methods) from functional components.

Before Hooks, you had to use class components to manage state or handle side effects. Hooks allow you to use these capabilities in functional components, which are simpler and easier to test.

Common React Hooks:

Hook

Description

useState

Lets you add local state to a functional component.

useEffect

Lets you perform side effects (e.g., fetching data, setting up subscriptions).

useContext

Access context data in a component.

useRef

Create a mutable reference that doesn’t cause re-renders. Often used to access DOM nodes.

useMemo

Optimize performance by memoizing expensive calculations.

useCallback

Memoizes a function to prevent unnecessary re-creations on every render.

useReducer

An alternative to useState for more complex state logic.


Example: useState and useEffect

jsx

CopyEdit

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


function Counter() {

  const [count, setCount] = useState(0);


  useEffect(() => {

    document.title = `Count is ${count}`;

  }, [count]);


  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click Me

      </button>

    </div>

  );

}



Why Use Hooks?

  • Simplify component logic.

  • Reuse stateful logic via custom hooks.

  • Avoid class boilerplate.

  • Improve readability and testing.


Axios is a JavaScript library used to make HTTP requests from web browsers or Node.js applications. It allows you to send and receive data from servers — typically APIs — in a simple, promise-based way.

Key Features of Axios:

  • Supports GET, POST, PUT, DELETE, and other HTTP methods

  • Works in both browser and Node.js

  • Promise-based: allows .then() and async/await usage

  • Automatically transforms JSON data

  • Allows you to set custom headers

  • Supports request and response interceptors

  • Handles timeouts and errors easily

  • Can cancel requests using a token

  • Supports CSRF/XSRF protection

import axios from 'axios';


// GET request

axios.get('https://api.example.com/data')

  .then(response => {

    console.log(response.data);  // handle data

  })

  .catch(error => {

    console.error('Error fetching data:', error);

  });


// POST request

axios.post('https://api.example.com/users', {

  name: 'John Doe',

  age: 30

})

.then(response => {

  console.log('User created:', response.data);

})

.catch(error => {

  console.error('Error creating user:', error);

});

To install Axios on Linux, you need to have Node.js and npm (Node Package Manager) installed. Axios is a promise-based HTTP client for the browser and Node.js, commonly used in React and Node applications.


Install Axios Globally (optional)

bash

CopyEdit

sudo npm install -g axios

3. Install Axios in a Local Project

First, navigate to your project directory or create a new one:

bash

CopyEdit

mkdir myproject

cd myproject

npm init -y  # Initializes a package.json file


Then install Axios:

bash

CopyEdit

npm install axios


This will add Axios as a dependency in your package.json.


4. Use Axios in Your Code

Create a simple test file like test.js:

js

CopyEdit

const axios = require('axios');


axios.get('https://api.github.com')

  .then(response => {

    console.log(response.data);

  })

  .catch(error => {

    console.error(error);

  });


Run it:

bash

CopyEdit

node test.js


Can ssh into compute engine



import axios from 'axios'; 


function App() {

 const [name, setName] = useState(''); 

 const [address, setAddress] = useState('');

 const [result, setResult] = useState('');

 

 const handleGetRequest = () => { 

  axios

    .get('http://34.27.95.43:5000/')

.then((response) => {

setResult(JSON.stringify(response.data, null, 2));

}) 

.catch((error) => {

setResult(`Error: ${error.message}`);

});

};



  const handlePostRequest = () => {

  if (!name || !address){ 

    alert('Please fill in both Name and Address.');

return;

  axios

   .post(''http://34.27.95.43:5000/submit', { name, address }, {

   headers: { 'Content-Type': 'application/json' }

   }) 

   .then((response) => { 

   setResult(JSON.stringify(response.data, null, 2)); 

   })

   .catch((error) => { 

     setResult(`Error: ${error.message}`); 

});

 };

 

 return ( <div className="App" style={{ maxWidth: 500, margin: '0 auto', padding: '20px' }}> <h1>Submit Your Info</h1> <div style={{ marginBottom: 10 }}> <label>Name:</label><br /> <input type="text" value={name} onChange={(e) => setName(e.target.value)} style={{ width: '100%', padding: 8 }} /> </div> <div style={{ marginBottom: 10 }}> <label>Address:</label><br /> <input type="text" value={address} onChange={(e) => setAddress(e.target.value)} style={{ width: '100%', padding: 8 }} /> </div> <button onClick={handlePostRequest} style={{ marginRight: 10 }}>POST Request</button> <button onClick={handleGetRequest}>GET Request</button> <pre style={{ marginTop: 20, background: '#f4f4f4', padding: 10 }}>{result}</pre> </div> ); } export default App;

Backend process


Flask is a lightweight web framework written in Python. It’s used to build web applications quickly and with minimal boilerplate code. Flask is considered a microframework because it doesn’t include tools and libraries like database abstraction layers or form validation by default—though you can easily add these through extensions.



Flask CORS (Cross-Origin Resource Sharing) is a mechanism used in web development to allow a Flask web application (typically the backend API) to be accessed by web pages hosted on a different domain (the frontend, often running on another server or port during development).

Why You Need Flask CORS

By default, web browsers block requests made from a webpage hosted on one origin (domain + port) to a server on another. This is known as the Same-Origin Policy.

For example, if your frontend is running at http://localhost:3000 and your Flask API is at http://localhost:5000, the browser will block frontend requests to the backend unless you explicitly allow it with CORS.

jsonify is a function in Flask, a Python web framework, used to convert Python data structures (like dictionaries or lists) into a JSON (JavaScript Object Notation) response.

Example:

python

CopyEdit

from flask import Flask, jsonify


app = Flask(__name__)


@app.route('/data')

def get_data():

    data = {"name": "John", "age": 30}

    return jsonify(data)


What it does:

  • Converts data into JSON format.

  • Sets the Content-Type header to application/json.

  • Returns a proper HTTP response.





john_iacovacci1@sentiment-prod:~$ cd backend

john_iacovacci1@sentiment-prod:~/backend$ ls

app.py

john_iacovacci1@sentiment-prod:~/backend$ cat app.py



john_iacovacci1@sentiment-prod:~/backend$ cat app.py

from flask import Flask, request, jsonify

from flask_cors import CORS

app = Flask(__name__)


CORS(app) # allow React frontend to access this backend

@app.route('/')

def home():

   return "Hello from Flask!"


@app.route('/submit', methods=['POST'])

def submit():

    data = request.json 

    name = data.get('name')

    address = data.get('address')

    print(f"You entered: Name={name}, Address={address}")

    return jsonify({'message': f'You sent name: {name} and address: {address}'})


if __name__ == '__main__':

    app.run(host='0.0.0.0', port=5000, debug=True)

john_iacovacci1@sentiment-prod:~/backend$ 


Last login: Mon Jun 23 16:02:05 2025 from 35.235.244.33

john_iacovacci1@sentiment-prod:~$ cd backend

john_iacovacci1@sentiment-prod:~/backend$ ls

app.py

john_iacovacci1@sentiment-prod:~/backend$ python3 app.py

 * Serving Flask app 'app'

 * Debug mode: on

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

 * Running on all addresses (0.0.0.0)

 * Running on http://127.0.0.1:5000

 * Running on http://10.128.0.6:5000

Press CTRL+C to quit

 * Restarting with stat

 * Debugger is active!

 * Debugger PIN: 293-754-967



No comments:

Post a Comment

Notes 3-18-25

https://uconn-sa.blogspot.com/  We were able to launch an app engine program from our compute engine instance.   I'd like to get all wo...