DEV Community

Neelakandan R
Neelakandan R

Posted on

React js-Axios,usestate,useeffect

What is Axios?

Axios is a promise-based HTTP client for JavaScript that simplifies making HTTP requests from both the browser and Node.js environments. It supports all modern browsers and works well in React applications for interacting with APIs and handling HTTP requests.

Key Features of Axios

Promise-based API.

Works in both NodeJS and browsers.

Automatically transforms JSON data.

Supports request and response interceptors.

Allows easy handling of timeouts and cancellation of requests.

supports making GET, POST, PUT, DELETE, and other HTTP requests.

Setting Up Axios in a React Application

Before we start making HTTP requests with Axios, you need to install it. If you’re starting a new React project, create one first using create-react-app (if you haven’t already).

Step 1: Install Axios

To install Axios, run the following command in your React project’s root directory:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 2: Import Axios into Your Component

In your React component, import Axios at the top

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Axios as Dependency

Install Axios library using the command given below

npm i axios

Enter fullscreen mode Exit fullscreen mode

Example:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    console.log('Data received:', response.data);
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Enter fullscreen mode Exit fullscreen mode

useState

state could only be used in class components. But now, with hooks like useState, you can use state in functional components too.

const [state, setState] = useState(initialState)
Enter fullscreen mode Exit fullscreen mode

state: It is the value of the current state.

setState: It is the function that is used to update the state.

initialState: It is the initial value of the state.

How Does useState() Work?

The useState() hook allows you to add state to functional components in React. It works by:

  1. Initialize State: When you call useState(initialValue), it creates a state variable and an updater function.

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

  1. State is Preserved Across Renders: React remembers the state value between re-renders of the component. Each time the component renders, React keeps the latest value of count.

  2. State Updates with the Updater Function: When you call setCount(newValue) React updates the state and it re-renders the component to reflect the new state value.

setCount(count + 1)}>Increment

  1. Triggers Re-render: React will re-render only the component where useState was used—ensuring your UI updates automatically when the state changes.

Why useState is Helpful:

You can easily track changes in your component.

No need for complex code like in class components.

Counter using useState

A common example of using useState is managing the state of a counter with actions to increment and decrement the value.

import { useState } from 'react';
export default function Counter() {
    const [count, setCount] = useState(0);

    function handleClick() {
        setCount(count + 1);
    }
    return (
        <button onClick={handleClick}>
            Click {count} me
        </button>
    );
}
Enter fullscreen mode Exit fullscreen mode

What is useEffect?

useEffect is a React hook that lets you handle side effects in functional components. Side effects are things like:

Fetching data from an API

Setting up a timer

Updating the DOM directly

Subscribing to events

Why Use useEffect?

In class components, side effects like data fetching were handled in lifecycle methods like componentDidMount and componentDidUpdate.

import React, { useEffect } from 'react';

const SimpleEffect = () => {
  useEffect(() => {
    // This runs once when the component is loaded
    console.log("Component has loaded!");

  }, []); // Empty array means it runs only once, when the component mounts

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

export default SimpleEffect;


Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
mariaalba profile image
Maria • Edited

` import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useParams, useNavigate } from 'react-router-dom';

function Profile() {
  const { id } = useParams();
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newImage, setNewImageUrl] = useState('');
  const [profileImage, setProfileImage] = useState('')
  const [showImageInput, setShowImageInput] = useState(false);
  const [isImageUpdating, setIsImageUpdating] = useState(false);
Enter fullscreen mode Exit fullscreen mode

const url = 'your api url'

  // change name                 
 const [showNameInput, setShowNameInput] = useState(false);
  const [newName, setNewName] = useState('');
  const [isNameUpdating, setIsNameUpdating] = useState(false);
  const navigate = useNavigate();
  useEffect(() => {
    const url = `${api url}/${id}`;

    axios.get(url)
      .then(response => {
        const userData = response.data;
        setUser(userData);
        setProfileImage(userData.avatar || profileImage);
        setNewName(userData.fullName || '');
        setLoading(false);
      })
      .catch(err => {
        setError('error');
        setLoading(false);
        console.error(err);
      });
  }, [id]);
  const handleUpdateImage = () => {
    if (!newImage.trim()) {
      alert('enter valid URL image');
      return;
    }
    setIsImageUpdating(true);

    axios.put(
      `${api url}/${id}`,
      { ...user, avatar: newImage }
    )
      .then(res => {
        setProfileImage(newImage);
        setUser(res.data);
        setIsImageUpdating(false);
        setShowImageInput(false);
        alert('picture has changed!');
      })
      .catch(err => {
        console.error( err);
        alert('error during change photo');
        setIsImageUpdating(false);
      });
  };

  const handleDeleteAccount = () => {
    if (!window.confirm('are you sure want delete account?)) {
      return;
    }

    axios.delete(`${url}/${id}`)
      .then(() => {
        alert('account has deleted');


        const storedUser = JSON.parse(localStorage.getItem('user'));
        if (storedUser && storedUser.id === user.id) {
          localStorage.removeItem('user');
          window.dispatchEvent(new Event('storage')); 
        }


        navigate('/login');
      })
      .catch(err => {
        console.error(err);
        alert('please try again);
      });
  };

  const handleUpdateName = () => {
    if (!newName.trim()) {
      alert('enter valid name');
      return;
    }

    setIsNameUpdating(true);

    axios.put(
      `${api url}/${id}`,
      { ...user, fullName: newName }
    )
      .then(res => {
        setUser(res.data);
        setIsNameUpdating(false);
        setShowNameInput(false);
        alert('name changed!');

        const storedUser = JSON.parse(localStorage.getItem('user'));
        if (storedUser) {
          localStorage.setItem('user', JSON.stringify({
            ...storedUser,
            fullName: newName
          }));
        }
      })
      .catch(err => {
        console.error('error:', err);
        alert('error during change name.');
        setIsNameUpdating(false);
      });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center">
        <p className="text-black text-xl">Loading </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className=" min-h-screen flex items-center justify-center">
        <p className="text-red-300 text-xl">{error}</p>
      </div>
    );
  }

  return (
    <div className=" min-h-screen flex items-center justify-center p-4">
      <div className="w-full max-w-4xl rounded-2xl bg-white p-10 font-normal leading-relaxed text-gray-900 shadow-xl">
        <div className="flex flex-col md:flex-row">

          <div className="md:w-1/3 text-center mb-8 md:mb-0">
            <img
              src={profileImage}
              alt=""
              className="rounded-full w-48 h-48 mx-auto mb-4 border-4 border-cyan-800  "
            />


            <button
              onClick={() => setShowImageInput(!showImageInput)}
              className="mt-2 bg-cyan-800 text-white px-4 py-2 rounded-lg hover:bg-cyan-900 transition-colors duration-300 "
            >
              {showImageInput ? 'cancel' : ' Edite'}
            </button>

            {showImageInput && (
              <>
                <input
                  type="text"
                  placeholder="Enter Url of new Image"
                  value={newImage}
                  onChange={(e) => setNewImageUrl(e.target.value)}
                  className="w-full p-2 mt-2 mb-2 border border-gray-300 rounded"
                />
                <button
                  onClick={handleUpdateImage}
                  disabled={isImageUpdating}
                  className={`w-full mt-2 bg-black text-white py-2 rounded ${
                    isImageUpdating ? 'bg-black cursor-not-allowed' : 'hover:bg-gray-700'
                  }`}
                >
                  {isImageUpdating ? ' Saving.' : ' Save'}
                </button>
              </>
            )}
          </div>


          <div className="md:w-2/3 md:pl-8">

            <div className="flex items-center justify-between">
              <h1 className="text-2xl font-bold text-cyan-800 mb-2">
                {user.fullName || 'Full Name '}
              </h1>
              <button
                onClick={() => setShowNameInput(!showNameInput)}
                className="text-sm text-cyan-700 underline hover:text-cyan-900"
              >
                Edit
              </button>
            </div>


            {showNameInput && (
              <div className="mb-4">
                <input
                  type="text"
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  placeholder=" Enter new name "
                  className="w-full p-2 border border-gray-300 rounded mb-2"
                />
                <button
                  onClick={handleUpdateName}
                  disabled={isNameUpdating}
                  className={`w-full bg-black text-white py-2 rounded ${
                    isNameUpdating ? 'bg-black cursor-not-allowed' : 'hover:bg-gray-700'
                  }`}
                >
                  {isNameUpdating ? ' Saving' : ' Save'}
                </button>
              </div>
            )}
            <h2 className="text-xl font-semibold text-cyan-800 mb-4"> Other Info</h2>
            <ul className="space-y-2 text-gray-700">
              <li className="flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2 text-cyan-800" viewBox="0 0 20 20" fill="currentColor">
                  <path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" />
                  <path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" />
                </svg>
                {user.email}
              </li>
              <li className="flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2 text-cyan-800" viewBox="0 0 20 20" fill="currentColor">
                  <path d="M2 3a1 1 0 011-1h2.153a1 1 0 01.986.836l.74 4.435a1 1 0 01-.54 1.06l-1.548.773a11.037 11.037 0 006.105 6.105l.774-1.548a1 1 0 011.059-.54l4.435.74a1 1 0 01.836.986V17a1 1 0 01-1 1h-2C7.82 18 2 12.18 2 5V3z" />
                </svg>
                +966 (55) 123-4567
              </li>
              <li className="flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2 text-cyan-800" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                </svg>
             Riyadh, Kingdom of Saudi Arabia
              </li>
            </ul>
          </div>
        </div>
<div className="mt-6">
  <button
    onClick={handleDeleteAccount}
    className="w-full bg-red-600 hover:bg-red-700 text-white py-2 rounded"
  >
Delete Account
  </button>
</div>
      </div>
    </div>
  );
}

export default Profile;`
Enter fullscreen mode Exit fullscreen mode