Intermediate example of useState and useEffect with fetch API ?
here we are using select and useState, useEffect and JSONStringify
so once the option is selected our component will basically render the stats of the fruits if this doesn't work on your computer throw some CORS error install one plugin
Moesif Origin & CORS Changer
Code
import React, { useState, useEffect } from 'react'
import './First.css'
const First = () => {
const [fruit, setOption] = useState('banana')
const [fruitInfo, setFruitInfo] = useState()
const options = [
{
label: 'Apple',
value: 'apple',
},
{
label: 'Mango',
value: 'mango',
},
{
label: 'Banana',
value: 'banana',
},
{
label: 'Pineapple',
value: 'pineapple',
},
]
const onSelectedValue = (e) => {
setOption(e.target.value)
}
const fetchFruits = () => {
fetch(`https://www.fruityvice.com/api/fruit/${fruit}`)
.then((response) => response.json())
.then((json) => {
setFruitInfo(json)
})
}
useEffect(() => {
fetchFruits()
}, [fruit])
return (
<div>
<h1>this is cool</h1>
<div className='select-div'>
<select value={fruit} onChange={(e) => onSelectedValue(e)}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
<p> {JSON.stringify(fruitInfo)}</p>
<h5>
Carbohydrate in {fruit} is{' '}
{JSON.stringify(fruitInfo.nutritions.carbohydrates)}
</h5>
</div>
</div>
)
}
export default First