Skip to content

Commit 481140b

Browse files
API CALLS
1 parent 7c224b6 commit 481140b

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

react.js

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1477,4 +1477,52 @@ import ( useParams ) from 'react-router-dom';
14771477
const { blogPost } = useParams(); // assuming we are in a <Route>: /blog/:blogPost
14781478
const FunctionalComponent = () => {
14791479
return <p>{blogPost}</p> // /blog/test will render 'test'
1480-
};
1480+
};
1481+
1482+
1483+
1484+
// API CALLS
1485+
1486+
// external file with logic (./services/productService)
1487+
const baseUrl = process.env.REACT_APP_API_BASE_URL; // local url eg: http://localhost:3001/ or prod url eg: https://rembertdesigns.co
1488+
export async function getProducts(category) {
1489+
const response = await fetch(baseUrl + 'products?category=' + category);
1490+
if (response.ok) return response.json();
1491+
throw response;
1492+
}
1493+
// app file
1494+
import React, { useState, useEffect } from 'react';
1495+
import { getProducts } from './services/productService';
1496+
export default function App() {
1497+
const [products, setProducts] = useState([]);
1498+
const [error, setError] = useState(null);
1499+
const [loading, setLoading] = useState(true);
1500+
// with promises
1501+
useEffect(() => {
1502+
getProducts('shoes')
1503+
.then((response) => setProducts(response))
1504+
.catch((e) => setError(e))
1505+
.finally(() => setLoading(false));
1506+
}, []);
1507+
// with async/await
1508+
useEffect(() => {
1509+
async function init() {
1510+
try {
1511+
const response = await getProducts('shoes');
1512+
setProducts(response);
1513+
} catch (e) {
1514+
setError(e);
1515+
} finally {
1516+
setLoading(false);
1517+
}
1518+
}
1519+
init();
1520+
}, []);
1521+
return (
1522+
<section>
1523+
{products.map((p) => (
1524+
<p>{p.name}</p>
1525+
))}
1526+
</section>
1527+
)
1528+
}

0 commit comments

Comments
 (0)