source:
my-react-app/src/components/RestaurantContext.js
Last change on this file was c44c5ed, checked in by , 2 weeks ago | |
---|---|
|
|
File size: 836 bytes |
Rev | Line | |
---|---|---|
[cfc16a3] | 1 | import React, { createContext, useState, useEffect } from 'react'; |
2 | import axios from 'axios'; | |
3 | ||
4 | export const RestaurantContext = createContext(); | |
5 | ||
6 | export const RestaurantProvider = ({ children }) => { | |
7 | const [restaurants, setRestaurants] = useState([]); | |
8 | ||
9 | useEffect(() => { | |
[2518b3a] | 10 | if (restaurants.length > 0) return; |
[cfc16a3] | 11 | const fetchRestaurants = async () => { |
12 | try { | |
[8ca35dc] | 13 | const response = await axios.get('http://localhost:8081/api/restaurants'); |
[cfc16a3] | 14 | setRestaurants(response.data); |
15 | } catch (error) { | |
16 | console.error('Error fetching restaurants:', error); | |
17 | } | |
18 | }; | |
[f5b256e] | 19 | fetchRestaurants(); |
[cfc16a3] | 20 | }, []); |
21 | ||
22 | return ( | |
23 | <RestaurantContext.Provider value={{ restaurants }}> | |
24 | {children} | |
25 | </RestaurantContext.Provider> | |
26 | ); | |
27 | }; |
Note:
See TracBrowser
for help on using the repository browser.