import React, { useState, useEffect, useContext } from "react"; import Paper from '@mui/material/Paper'; import { useParams, useNavigate } from "react-router-dom"; import './Location.css'; import { GlobalContext } from "./GlobalContext.js"; import { base } from "./Common.js"; function Location(props) { const propLocation = props.location; const { csrfToken } = useContext(GlobalContext); const [googleApiKey, setGoogleApiKey] = useState(undefined); const [ location, setLocation ] = useState( typeof propLocation === 'object' ? propLocation : undefined); const [ error, setError ] = useState(null); const locationId = typeof propLocation === 'number' ? propLocation : undefined; useEffect(() => { if (!csrfToken || googleApiKey) { return; } const effect = async () => { const res = await window.fetch( `${base}/api/v1/locations/google-api-key`, { method: 'GET', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'CSRF-Token': csrfToken } }); const data = await res.json(); if (res.status >= 400) { setError(data.message ? data.message : res.statusText); return; } if (!data) { return; } setGoogleApiKey(data.key); } effect(); }, [csrfToken, googleApiKey, setGoogleApiKey]); useEffect(() => { if (!csrfToken || location || !locationId) { return; } const effect = async () => { const res = await window.fetch( `${base}/api/v1/locations/${locationId}`, { method: 'GET', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'CSRF-Token': csrfToken } }); const data = await res.json(); if (res.status >= 400) { setError(data.message ? data.message : res.statusText); return; } if (!data) { return; } setLocation(data); } effect(); }, [locationId, csrfToken, location]); const createLocation = (location) => { const fields = Object.getOwnPropertyNames(location) .filter(field => location[field]) .map(field => { return