File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -1526,3 +1526,50 @@ export default function App() {
15261526 </ section >
15271527 )
15281528}
1529+
1530+
1531+
1532+ // API CALL WITH CUSTOM HOOK
1533+
1534+ // external custom hook
1535+ import { useState , useEffect } from 'react' ;
1536+ // local url eg: http://localhost:3001/ or prod url eg: https://rembertdesigns.co
1537+ const baseUrl = process . env . REACT_APP_API_BASE_URL ;
1538+ export default function useFetch ( url ) {
1539+ const [ data , setData ] = useState ( null ) ;
1540+ const [ error , setError ] = useState ( null ) ;
1541+ const [ loading , setLoading ] = useState ( true ) ;
1542+ useEffect ( ( ) => {
1543+ async function init ( ) {
1544+ try {
1545+ const response = await fetch ( baseUrl + url ) ;
1546+ if ( response . ok ) {
1547+ const json = await response . json ( ) ;
1548+ setData ( json ) ;
1549+ } else {
1550+ throw response ;
1551+ }
1552+ } catch ( e ) {
1553+ setError ( e ) ;
1554+ } finally {
1555+ setLoading ( false ) ;
1556+ }
1557+ }
1558+ init ( ) ;
1559+ } , [ url ] ) ;
1560+ return { data, error, loading } ;
1561+ }
1562+
1563+ // app file
1564+ import React , { useState } from 'react' ;
1565+ import useFetch from './services/useFetch' ;
1566+ export default function App ( ) {
1567+ const { data : products , loading, error, } = useFetch ( 'products?category=shoes' ) ;
1568+ return (
1569+ < section >
1570+ { products . map ( ( p ) => (
1571+ < p > { p . name } </ p >
1572+ ) ) }
1573+ </ section >
1574+ )
1575+ }
You can’t perform that action at this time.
0 commit comments