|
1 | 1 | import { useEffect, useState } from "react"; |
2 | 2 | import useLocalStorage from "./useLocalStorage"; |
| 3 | +import { ALL_PROVIDERS } from "src/utils/constants"; |
3 | 4 |
|
4 | | -const useGetOpportunities = (postParams) => { |
| 5 | +function fetchOpportunity(token, provider, params){ |
| 6 | + return fetch("/api/opportunities", { |
| 7 | + method: "POST", |
| 8 | + headers: { |
| 9 | + "Content-type": "application/json", |
| 10 | + "Backend": provider, |
| 11 | + 'Authorization': `Bearer ${token}` |
| 12 | + }, |
| 13 | + body: JSON.stringify(params) |
| 14 | + }); |
| 15 | +}; |
| 16 | + |
| 17 | +const useGetOpportunities = (products, postParams) => { |
5 | 18 | const {params, provider} = !!postParams && postParams; |
6 | 19 | const [data, setData] = useState(null); |
7 | 20 | const [isLoading, setIsLoading] = useState(false); |
8 | 21 | const [error, setError] = useState(""); |
9 | 22 | const { userToken } = useLocalStorage(); |
10 | 23 |
|
| 24 | + function fetchAllProviderProducts(p){ |
| 25 | + return products[p] && products[p].map(async product => { |
| 26 | + return fetchOpportunity(userToken, p, Object.assign(params, {"product_id": product.id})).then(async res => await res.json()).then(data => { return {'provider': p, 'data': data}}); |
| 27 | + }); |
| 28 | + }; |
| 29 | + |
11 | 30 | useEffect(() => { |
12 | 31 | if (params) { |
13 | 32 | setIsLoading(true); |
14 | 33 | setError(false); |
15 | | - fetch("/api/opportunities", { |
16 | | - method: "POST", |
17 | | - headers: { |
18 | | - "Content-type": "application/json", |
19 | | - "Backend": provider, |
20 | | - 'Authorization': `Bearer ${userToken}` |
21 | | - }, |
22 | | - body: JSON.stringify(params) |
23 | | - }) |
24 | | - .then((res) => res.json()) |
25 | | - .then((data) => { |
26 | | - setData(data.features) |
27 | | - setIsLoading(false) |
28 | | - }).catch(e => { |
29 | | - setError(e); |
30 | | - setIsLoading(false); |
31 | | - }); |
| 34 | + // By default fetch all provider product opportunities |
| 35 | + if(!provider && !params["product_id"]){ |
| 36 | + const allProvidersOpportunities = ALL_PROVIDERS.reduce((all, p) => { |
| 37 | + const promises = fetchAllProviderProducts(p.id); |
| 38 | + return promises ? [...all, ...promises] : all; |
| 39 | + }, []); |
| 40 | + |
| 41 | + Promise.all(allProvidersOpportunities).then(results => { |
| 42 | + setData(Object.fromEntries(Object.values(results).map(value => { |
| 43 | + return [value.provider, value.data.features] |
| 44 | + }))); |
| 45 | + setIsLoading(false); |
| 46 | + }).catch(e => { |
| 47 | + setError(e); |
| 48 | + setIsLoading(false); |
| 49 | + }); |
| 50 | + } |
32 | 51 | } |
33 | 52 | }, [params, provider]); |
34 | 53 |
|
|
0 commit comments