Skip to content

Commit

Permalink
#36 Add logic to get and post locations
Browse files Browse the repository at this point in the history
  • Loading branch information
SandraBergstrom committed Jun 30, 2023
1 parent 8439ec4 commit 6da7269
Showing 1 changed file with 67 additions and 22 deletions.
89 changes: 67 additions & 22 deletions src/components/LocationForm.js
Original file line number Diff line number Diff line change
@@ -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 (
<form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label htmlFor="locationName">Name of location:</Form.Label>
<input
type="text"
name="name"
value={location}
onChange={handleLocationChange}
/>
</Form.Group>
<Form.Group>
<Form.Label htmlFor="country">Country:</Form.Label>
<Form.Control as="select" onChange={handleCountryChange}>
<option key={country.name} value={country.name}></option>
</Form.Control>
</Form.Group>
</form>
);
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 (
<form onSubmit={handleLocationFormSubmit}>
<Form.Group>
<Form.Label htmlFor="locationName">Name of location:</Form.Label>
<input
type="text"
name="name"
value={locationName}
onChange={handleLocationChange}
/>
</Form.Group>
<Form.Group>
<Form.Label htmlFor="country">Country:</Form.Label>
<Form.Control as="select" onChange={handleCountryChange}>
{countries.map((country) => (
<option key={country.name.common} value={country.name.common}>
{country.name.common}
</option>
))}
</Form.Control>
</Form.Group>
</form>
);
};

export default LocationForm;

0 comments on commit 6da7269

Please sign in to comment.