From 6da726999d89b15b1bbe47f31f2f2ae0fd739dfd Mon Sep 17 00:00:00 2001 From: SandraBergstrom Date: Fri, 30 Jun 2023 09:24:00 +0000 Subject: [PATCH] #36 Add logic to get and post locations --- src/components/LocationForm.js | 89 +++++++++++++++++++++++++--------- 1 file changed, 67 insertions(+), 22 deletions(-) diff --git a/src/components/LocationForm.js b/src/components/LocationForm.js index d3ebfa2..9ae3cc7 100644 --- a/src/components/LocationForm.js +++ b/src/components/LocationForm.js @@ -1,31 +1,76 @@ -import React, { useState } from "react"; -import axios from "axios"; +import React, { useEffect, useState } from "react"; import { Form } from "react-bootstrap"; +import { axiosReq, axiosRes } from "../api/axiosDefaults"; const LocationForm = () => { const [locationName, setLocationName] = useState(""); const [countries, setCountries] = useState([]); const [selectedCountry, setSelectedCountry] = useState(""); -}; -return ( -
- - Name of location: - - - - Country: - - - - -
-); + useEffect(() => { + // Fetch list of countries from Restcountries API + const fetchCountries = async () => { + try { + const response = await axiosReq.get( + "https://restcountries.com/v3.1/all" + ); + setCountries(response.data); + } catch (err) { + console.log("Error fetching countries:", err); + } + }; + fetchCountries(); + }, []); + + const handleLocationChange = (event) => { + setLocationName(event.target.value); + }; + + const handleCountryChange = (event) => { + setSelectedCountry(event.target.value); + }; + + const handleLocationFormSubmit = async (event) => { + event.preventDefault(); + + // Create a new location + const newLocation = { + name: locationName, + country: selectedCountry, + }; + + try { + // Save location to Travel Tickr api + const response = await axiosRes.post("/locations/", newLocation); + console.log("Location saved successfully", response.data); + } catch (err) { + console.error("Error saving location:", err); + } + }; + + return ( +
+ + Name of location: + + + + Country: + + {countries.map((country) => ( + + ))} + + +
+ ); +}; export default LocationForm;