Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save I-keep-trying/39c0dd979c0ec52c136aa12a2377ac46 to your computer and use it in GitHub Desktop.
Save I-keep-trying/39c0dd979c0ec52c136aa12a2377ac46 to your computer and use it in GitHub Desktop.
cannot set state
import React, { useState, useEffect } from 'react'
const countriesList = [
{ name: 'Afghanistan' },
{ name: 'Åland Islands' },
{ name: 'Albania' },
{ name: 'Algeria' },
{ name: 'American Samoa' },
{ name: 'Andorra' },
{ name: 'Angola' },
]
const Header = ({ input, handleChange, handleSubmit }) => {
return (
<form onSubmit={handleSubmit}>
Input:{' '}
<input
style={{ border: '1px solid blue' }}
type="text"
value={input}
onChange={handleChange}
/>
</form>
)
}
function App() {
const [countries, setCountries] = useState(countriesList)
const [searchTerm, setSearchTerm] = useState('')
const [input, setInput] = useState('')
console.log('countries global', countries)
// HOW DO YOU 'setCountries' TO THE FILTERED LIST???
const filteredCountries = countries.filter(country => {
return country.name.toLowerCase().startsWith(searchTerm.toLowerCase())
? country
: null
})
console.log('filtered countries', filteredCountries) // returns filtered countries
//setCountries(filteredCountries) // too many rerenders
// WITH USEEFFECT?
useEffect(() => {
console.log('useEffect filtered', filteredCountries) // returns filtered countries
setCountries(filteredCountries)
// app is completely crippled & frozen with 'filteredCountries as a dependency,
// but with no dependency, 'setCountries' does not do anything
}, [])
// HANDLECHANGE IS SET ON EACH KEYSTROKE
const handleChange = event => {
event.preventDefault()
setInput(event.target.value)
}
// HANDLESUBMIT IS SEPARATE SO INPUT CAN BE SET TO ''
// also I plan to add a button to call this instead of 'enter'
const handleSubmit = e => {
e.preventDefault()
setSearchTerm(input)
setInput('')
}
console.log('countries global after useEffect', countries)
const countryDetail = () => {
console.log('countryDetail',filteredCountries)
return filteredCountries.map(country => {
return (
<div>
Name: {country.name} Capital: {country.capital}
</div>
)
})
}
return (
<div>
<Header
input={input}
searchTerm={searchTerm}
handleChange={handleChange}
handleSubmit={handleSubmit}
/>
<div>{JSON.stringify(countries)}</div>
</div>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment