Created
August 16, 2020 20:52
-
-
Save YBCS/a0a36f2c0a0a90dc52c860689f070312 to your computer and use it in GitHub Desktop.
fullstack part 7 ex 7.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ex 7.7 | |
const useCountry = (name) => { | |
const [country, setCountry] = useState(null) | |
useEffect(() => { | |
if (name !== '') { | |
axios.get(`https://restcountries.eu/rest/v2/name/${name}?fullText=true`) | |
.then((response) => { | |
setCountry({...response, found: true}) | |
}).catch((e) => { | |
console.log(e) | |
setCountry({found: false}) | |
}) | |
} | |
}, [name]) | |
return country | |
} | |
const Country = ({ country }) => { | |
if (!country) { | |
return null | |
} | |
if (!country.found) { | |
return <div>not found...</div> | |
} | |
// this is very hacky.. I dont know how to do it otherwise tho | |
country.data = country.data[0] | |
return ( | |
<div> | |
<h3>{country.data.name} </h3> | |
<div>capital {country.data.capital} </div> | |
<div>population {country.data.population}</div> | |
<img | |
src={country.data.flag} | |
height='100' | |
alt={`flag of ${country.data.name}`} | |
/> | |
</div> | |
) | |
} | |
const App = () => { | |
const nameInput = useField('text') | |
const [name, setName] = useState('') | |
const country = useCountry(name) | |
const fetch = (e) => { | |
e.preventDefault() | |
setName(nameInput.value) | |
} | |
return ( | |
<div> | |
<form onSubmit={fetch}> | |
<input {...nameInput} /> | |
<button>find</button> | |
</form> | |
<Country country={country} /> | |
</div> | |
) | |
} | |
export default App | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment