0

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!

Lidder Dj
  • 5
  • 1

2 Answers2

0

onClick handlers expect their argument to be the event, which in this case is the click. When you write

  const handleShow = (country) => {
    setCountryDetail(country)
    console.log({countryDetail})
  }

You are setting the country to be the click event. Even though you wrote the function as const handleShow = country =>, its being read as const handleShow = event of the onClick =>. You need to pass the country detail in your clickHandler a little differently. Rather than just saying onClick={handleShow}, you can pass a callback function:

<button onClick={ () => {handleshow(country)} }> Show </button>

Now your handleShow function is not a function of the event, but rather of the country variable.

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
0

I think you're looking to implement something like this

React js onClick can't pass value to method

Try onClick={() => handleShow(country)}

possum
  • 1,837
  • 3
  • 9
  • 18