I'm having trouble passing values between a button on-click event and an event handler function to setState.
I have the following code:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import CountryDetail from './components/countryDetail'
import Filter from './components/filter'
const App = () => {
const [ countries, setCountries] = useState([])
const [ search, setSearch ] = useState("")
const [ countryDetail, setCountryDetail] = useState([])
useEffect(() => {
console.log('effect')
axios
.get('https://restcountries.eu/rest/v2/name/' + search)
.then(response => {
console.log('promise fulfilled')
setCountries(response.data)
})
}, [search])
console.log({countries})
const handleSearch = (event) => {
setSearch(event.target.value);
console.log(countries.length)
}
const handleShow = (country) => {
setCountryDetail(country)
console.log({countryDetail})
}
if (countries.length === 1) {
return (
<div>
<Filter search = {search} handleSearch = {handleSearch}/>
<CountryDetail countries={countries[0]}/>
</div>
)
}
return (
<div>
<Filter search = {search} handleSearch = {handleSearch}/>
<h2>Countries</h2>
<div>
{countries.map((country) => (
<div key={country.alpha3Code}>
<p>{country.name} <button onClick={handleShow}> Show </button></p>
</div>
))}
</div>
</div>
)
}
export default App
When you search for a country, the array returned is rendered. What I'm trying to do is setCountryDetail when the button associated with a particular country is clicked. In turn, countryDetail will be used to display additional detail about the particular country.
Any tips or advice would be greatly appreciated!