dijkstra-frontend/src/components/HomeView.jsx

127 lines
4.1 KiB
JavaScript

import React, { useState ,useEffect } from "react";
import Axios from '../utils/API';
import { Select, Button, Icon } from 'antd';
const { Option } = Select;
function HomeView() {
const [cities, setCities] = useState([]);
const [startingPoint, setStartingPoint] = useState();
const [destination, setDestination] = useState();
const [shortestPath, setShortestPath] = useState();
const [errorMessage, setErrorMessage] = useState();
useEffect(() => {
async function fetchData() {
try {
const { data } = await Axios.get(
`/countries/1`
);
setCities(data);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
function handleStart(city_id) {
// eslint-disable-next-line
let [ startingPoint ] = cities.filter(city => city.id == city_id);
setStartingPoint(startingPoint);
}
function handleDestination(city_id) {
// eslint-disable-next-line
let [ destination ] = cities.filter(city => city.id == city_id);
setDestination(destination);
}
function handleSubmit() {
if (startingPoint === destination) {
setErrorMessage('Starting Point and Destination must be different cities.');
return
} else if (startingPoint && destination) {
async function getPath() {
try {
const response = await Axios.get(
`/path`,
{
params: {
start_city_id: startingPoint.id,
end_city_id: destination.id
}
}
);
setShortestPath(response.data)
setErrorMessage();
} catch (error) {
console.error(error);
}
}
getPath();
} else {
setErrorMessage('Please select a Starting point and a Destination');
}
}
return(
<main>
<section>
<h2>Select Starting Point</h2>
<div>
<Select defaultValue="Belgium" disabled>
</Select>
<Select
defaultValue="Choose a city"
onChange={handleStart}
>
{cities.map(city => (
<Option key={city.id}>{city.name}</Option>
))}
</Select>
</div>
</section>
<section>
<h2>Select Destination</h2>
<div>
<Select defaultValue="Belgium" disabled>
</Select>
<Select
defaultValue="Choose a city"
onChange={handleDestination}
>
{cities.map(city => (
<Option key={city.id}>{city.name}</Option>
))}
</Select>
</div>
</section>
<section>
<Button
type="primary"
onClick={handleSubmit}
>
Get shortest path between the cities
<Icon type="right" />
</Button>
{errorMessage &&
<p>{errorMessage}</p>
}
</section>
{
shortestPath &&
<section>
<h2>Shortest path from {startingPoint.name} to {destination.name}</h2>
<p>{shortestPath.path.map(city => (
<><span>{city.name}</span><Icon type="right" /></>
))}
</p>
</section>
}
</main>
);
}
export default HomeView