Skip to content

Instantly share code, notes, and snippets.

@ohansemmanuel
Created April 14, 2019 12:37
Show Gist options
  • Save ohansemmanuel/b43b785b90836c7377f9a267dd025f4f to your computer and use it in GitHub Desktop.
Save ohansemmanuel/b43b785b90836c7377f9a267dd025f4f to your computer and use it in GitHub Desktop.
const fetchData = () => {
const stringifyData = data => JSON.stringify(data, null, 2)
const initialData = stringifyData({ data: null })
const loadingData = stringifyData({ data: 'loading...' })
const [data, setData] = useState(initialData)
const [gender, setGender] = useState('female')
const [loading, setLoading] = useState(false)
useEffect(
() => {
const fetchData = () => {
setLoading(true)
const uri = 'https://randomuser.me/api/?gender=' + gender
fetch(uri)
.then(res => res.json())
.then(({ results }) => {
setLoading(false)
const { name, gender, dob } = results[0]
const dataVal = stringifyData({
...name,
gender,
age: dob.age
})
setData(dataVal)
})
}
fetchData()
},
[gender]
)
return (
<>
<button
onClick={() => setGender('male')}
style={{ outline: gender === 'male' ? '1px solid' : 0 }}
>
Fetch Male User
</button>
<button
onClick={() => setGender('female')}
style={{ outline: gender === 'female' ? '1px solid' : 0 }}
>
Fetch Female User
</button>
<section>
{loading ? <pre>{loadingData}</pre> : <pre>{data}</pre>}
</section>
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment