Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useEffect } from "react";
- import axios from "axios";
- const App = () => {
- const [countries, setCountries] = useState([]);
- const [foundNames, setFoundNames] = useState([]);
- const [nameFilter, setNameFilter] = useState("");
- const [viewCountry, setViewCountry] = useState(-1);
- useEffect(() => {
- console.log("effect");
- axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
- console.log("promise fulfilled");
- setCountries(response.data);
- console.log(response.data);
- });
- }, []);
- const handleFilterChange = (event) => {
- setNameFilter(event.target.value);
- };
- const filterNames = (event) => {
- event.preventDefault();
- const objectNames = countries.filter(
- (country) => country.name.toLowerCase().search(nameFilter) > -1
- );
- setViewCountry(-1); //NOTE remember rules of hooks
- setFoundNames(objectNames);
- };
- const handleSearches = () => {
- if (foundNames.length >= 10) {
- return <div>Too many matches, specify another query</div>;
- }
- if (foundNames.length === 1) {
- console.log(foundNames[0].name);
- return (
- <div>
- <h2>{foundNames[0].name}</h2>
- <h2>capital: {foundNames[0].capital}</h2>
- <h2>population: {foundNames[0].population}</h2>
- <ul>
- {foundNames[0].languages.map((langs, index) => (
- <li key={index}> {langs.name}</li>
- ))}
- </ul>
- <img
- src={foundNames[0].flag}
- alt=""
- width="100"
- height="100"
- ></img>
- </div>
- );
- }
- if (viewCountry >= 0) {
- const temp = viewCountry;
- return (
- <div>
- <h2>{foundNames[temp].name}</h2>
- <h2>capital: {foundNames[temp].capital}</h2>
- <h2>population: {foundNames[temp].population}</h2>
- <ul>
- {foundNames[temp].languages.map((langs, index) => (
- <li key={index}> {langs.name}</li>
- ))}
- </ul>
- <img
- src={foundNames[temp].flag}
- alt=""
- width="100"
- height="100"
- ></img>
- </div>
- );
- }
- return (
- <div>
- <ul>
- {foundNames.map((country, index) => [
- <li key={country.name}>{country.name}</li>,
- <button
- key={country.name + index}
- onClick={() => setViewCountry(index)}
- >
- view
- </button>,
- ])}
- </ul>
- </div>
- );
- };
- return (
- <div>
- <h2>find Countries:</h2>
- <form onChange={filterNames}>
- <input value={nameFilter} onChange={handleFilterChange}></input>
- </form>
- <div>{handleSearches()}</div>
- </div>
- );
- };
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement