How to Handle Axios Requests in React with a Laravel API

This article will explore handling Axios Requests in React with a Laravel API that communicates with a Laravel backend. Axios is a promise-based HTTP client for the browser and Node.js, often used in front-end applications to make HTTP requests.

 

Prerequisites:

– Basic knowledge of Laravel (PHP)
– Familiarity with React (JavaScript)
– An existing Laravel API and React application

1. Setting Up the Laravel API

Before handling Axios requests in React, ensure your Laravel API is correctly set up.

  • Create a basic API route in `routes/api.php`:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    // routes/api.php
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\UserController;
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
    // routes/api.php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\UserController; Route::get('/users', [UserController::class, 'index']); Route::post('/users', [UserController::class, 'store']);
    // routes/api.php
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\UserController;
    
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
    
    
  • Create a basic `UserController` with index and store methods:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    // app/Http/Controllers/UserController.php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Models\User;
    class UserController extends Controller
    {
    public function index()
    {
    return response()->json(User::all(), 200);
    }
    public function store(Request $request)
    {
    $validatedData = $request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|email|unique:users',
    ]);
    $user = User::create($validatedData);
    return response()->json($user, 201);
    }
    }
    // app/Http/Controllers/UserController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { return response()->json(User::all(), 200); } public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', ]); $user = User::create($validatedData); return response()->json($user, 201); } }
    // app/Http/Controllers/UserController.php
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\User;
    
    class UserController extends Controller
    {
        public function index()
        {
            return response()->json(User::all(), 200);
        }
    
        public function store(Request $request)
        {
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users',
            ]);
    
            $user = User::create($validatedData);
    
            return response()->json($user, 201);
        }
    }
    
    

2. Setting Up Axios in React

    • Install Axios if you haven’t already:npm install axios
    • Create an Axios instance (optional):
      Plain text
      Copy to clipboard
      Open code in new window
      EnlighterJS 3 Syntax Highlighter
      // src/api/axios.js
      import axios from 'axios';
      const axiosInstance = axios.create({
      baseURL: 'http://localhost:8000/api', // Replace with your Laravel API URL
      headers: {
      'Content-Type': 'application/json',
      },
      });
      export default axiosInstance;
      // src/api/axios.js import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'http://localhost:8000/api', // Replace with your Laravel API URL headers: { 'Content-Type': 'application/json', }, }); export default axiosInstance;
      // src/api/axios.js
      import axios from 'axios';
      
      const axiosInstance = axios.create({
        baseURL: 'http://localhost:8000/api', // Replace with your Laravel API URL
        headers: {
          'Content-Type': 'application/json',
        },
      });
      
      export default axiosInstance;
      

3. Making GET Requests with Axios

  • Fetch data from your Laravel API and display it:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    // src/components/UserList.js
    import React, { useState, useEffect } from 'react';
    import axiosInstance from '../api/axios';
    const UserList = () => {
    const [users, setUsers] = useState([]);
    const [error, setError] = useState('');
    useEffect(() => {
    const fetchUsers = async () => {
    try {
    const response = await axiosInstance.get('/users');
    setUsers(response.data);
    } catch (err) {
    setError('Failed to fetch users');
    }
    };
    fetchUsers();
    }, []);
    return (
    <div>
    <h2>User List</h2>
    {error && <p style={{ color: 'red' }}>{error}</p>}
    <ul>
    {users.map(user => (
    <li key={user.id}>{user.name} - {user.email}</li>
    ))}
    </ul>
    </div>
    );
    };
    // src/components/UserList.js import React, { useState, useEffect } from 'react'; import axiosInstance from '../api/axios'; const UserList = () => { const [users, setUsers] = useState([]); const [error, setError] = useState(''); useEffect(() => { const fetchUsers = async () => { try { const response = await axiosInstance.get('/users'); setUsers(response.data); } catch (err) { setError('Failed to fetch users'); } }; fetchUsers(); }, []); return ( <div> <h2>User List</h2> {error && <p style={{ color: 'red' }}>{error}</p>} <ul> {users.map(user => ( <li key={user.id}>{user.name} - {user.email}</li> ))} </ul> </div> ); };
    // src/components/UserList.js
    import React, { useState, useEffect } from 'react';
    import axiosInstance from '../api/axios';
    
    const UserList = () => {
      const [users, setUsers] = useState([]);
      const [error, setError] = useState('');
    
      useEffect(() => {
        const fetchUsers = async () => {
          try {
            const response = await axiosInstance.get('/users');
            setUsers(response.data);
          } catch (err) {
            setError('Failed to fetch users');
          }
        };
    
        fetchUsers();
      }, []);
    
      return (
        <div>
          <h2>User List</h2>
          {error && <p style={{ color: 'red' }}>{error}</p>}
          <ul>
            {users.map(user => (
              <li key={user.id}>{user.name} - {user.email}</li>
            ))}
          </ul>
        </div>
      );
    };
    

    export default UserList;

    – We created a functional component, `UserList`.
    – Used `useState` and `useEffect` to manage state and perform data fetching upon mounting.
    – `axiosInstance.get(‘/users’)` sends a GET request to the `/users` endpoint.

4.  Making POST Requests with Axios

    • Create a form for adding new users:
      Plain text
      Copy to clipboard
      Open code in new window
      EnlighterJS 3 Syntax Highlighter
      // src/components/AddUserForm.js
      import React, { useState } from 'react';
      import axiosInstance from '../api/axios';
      const AddUserForm = () => {
      const [name, setName] = useState('');
      const [email, setEmail] = useState('');
      const [message, setMessage] = useState('');
      const handleSubmit = async (event) => {
      event.preventDefault();
      try {
      const response = await axiosInstance.post('/users', {
      name: name,
      email: email,
      });
      setMessage(`User ${response.data.name} added successfully!`);
      setName('');
      setEmail('');
      } catch (err) {
      setMessage('Failed to add user. Please try again.');
      }
      };
      return (
      <div>
      <h2>Add New User</h2>
      {message && <p>{message}</p>}
      <form onSubmit={handleSubmit}>
      <div>
      <label>Name:</label>
      <input
      type='text'
      value={name}
      onChange={(e) => setName(e.target.value)}
      required
      />
      </div>
      <div>
      <label>Email:</label>
      <input
      type='email'
      value={email}
      onChange={(e) => setEmail(e.target.value)}
      required
      />
      </div>
      <button type='submit'>Add User</button>
      </form>
      </div>
      );
      };
      // src/components/AddUserForm.js import React, { useState } from 'react'; import axiosInstance from '../api/axios'; const AddUserForm = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = async (event) => { event.preventDefault(); try { const response = await axiosInstance.post('/users', { name: name, email: email, }); setMessage(`User ${response.data.name} added successfully!`); setName(''); setEmail(''); } catch (err) { setMessage('Failed to add user. Please try again.'); } }; return ( <div> <h2>Add New User</h2> {message && <p>{message}</p>} <form onSubmit={handleSubmit}> <div> <label>Name:</label> <input type='text' value={name} onChange={(e) => setName(e.target.value)} required /> </div> <div> <label>Email:</label> <input type='email' value={email} onChange={(e) => setEmail(e.target.value)} required /> </div> <button type='submit'>Add User</button> </form> </div> ); };
      // src/components/AddUserForm.js
      import React, { useState } from 'react';
      import axiosInstance from '../api/axios';
      
      const AddUserForm = () => {
        const [name, setName] = useState('');
        const [email, setEmail] = useState('');
        const [message, setMessage] = useState('');
      
        const handleSubmit = async (event) => {
          event.preventDefault();
      
          try {
            const response = await axiosInstance.post('/users', {
              name: name,
              email: email,
            });
      
            setMessage(`User ${response.data.name} added successfully!`);
            setName('');
            setEmail('');
          } catch (err) {
            setMessage('Failed to add user. Please try again.');
          }
        };
      
        return (
          <div>
            <h2>Add New User</h2>
            {message && <p>{message}</p>}
            <form onSubmit={handleSubmit}>
              <div>
                <label>Name:</label>
                <input
                  type='text'
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                />
              </div>
              <div>
                <label>Email:</label>
                <input
                  type='email'
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>
              <button type='submit'>Add User</button>
            </form>
          </div>
        );
      };
      
      

      export default AddUserForm;

      – The component provides a form for adding users.
      – `handleSubmit` sends a POST request containing `name` and `email` da

5. Error Handling and Response Interception

  • You can add error handling and response interceptors if needed:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    // src/api/axios.js
    axiosInstance.interceptors.response.use(
    response => response,
    error => {
    if (error.response && error.response.status === 401) {
    console.error('Unauthorized access - redirecting to login...');
    }
    return Promise.reject(error);
    }
    );
    // src/api/axios.js axiosInstance.interceptors.response.use( response => response, error => { if (error.response && error.response.status === 401) { console.error('Unauthorized access - redirecting to login...'); } return Promise.reject(error); } );
    // src/api/axios.js
    axiosInstance.interceptors.response.use(
      response => response,
      error => {
        if (error.response && error.response.status === 401) {
          console.error('Unauthorized access - redirecting to login...');
        }
        return Promise.reject(error);
      }
    );
    
    

     

6. Combining Components in a Parent Component

      • Render `UserList` and `AddUserForm` components:
        Plain text
        Copy to clipboard
        Open code in new window
        EnlighterJS 3 Syntax Highlighter
        // src/App.js
        import React from 'react';
        import UserList from './components/UserList';
        import AddUserForm from './components/AddUserForm';
        function App() {
        return (
        <div>
        <h1>React and Laravel API Integration</h1>
        <AddUserForm />
        <UserList />
        </div>
        );
        }
        // src/App.js import React from 'react'; import UserList from './components/UserList'; import AddUserForm from './components/AddUserForm'; function App() { return ( <div> <h1>React and Laravel API Integration</h1> <AddUserForm /> <UserList /> </div> ); }
        // src/App.js
        import React from 'react';
        import UserList from './components/UserList';
        import AddUserForm from './components/AddUserForm';
        
        function App() {
          return (
            <div>
              <h1>React and Laravel API Integration</h1>
              <AddUserForm />
              <UserList />
            </div>
          );
        }
        

        export default App;

Conclusion

By following this guide, you now have a simple React frontend communicating with a Laravel API using Axios. You can enhance this example by adding features like form validation, loading states, or even authentication mechanisms with Laravel Sanctum. Axios makes handling HTTP requests easy, providing a flexible way to interact with APIs in your React applications.

Read Also :
How JavaScript Modules Work: ES6 Modules and CommonJS

Optimizing JavaScript for Performance and Faster Load Times

Also visit :
https://inimisttech.com/

Leave a Reply