Flask + CORS + jwt_required (js)

Format: JavaScript
 ( View Raw)
Date: Sun, 29 Dec 2024 at 10:47:23

import React, { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [products, setProducts] = useState([]); // State to hold products

  useEffect(() => {
    const fetchProducts = async () => {
      const login = await axios.get(`http://localhost:5000/login/`);
      const token = login.data["access_token"];
      const response = await axios.get(`http://localhost:5000/products/`, {
        headers: {
            Authorization: `Bearer ${token}`,
        },
      });
        setProducts(response.data); // Update state with fetched data
    };

    fetchProducts(); // Fetch products when the component mounts
  }, []); // Empty dependency array ensures this runs only once

  return (
    <div>
      <h1>Products</h1>
      {
        <ul>
          {products.map((product, index) => (
            <li key={index}>{JSON.stringify(product)}</li>
          ))}
        </ul>
      }
    </div>
  );
}

export default App;