Listing 11-8: Asynchronous Requests with useEffect
import {useEffect, useState} from 'react';
function ShippingAddress(props){
const [zipcode,setZipcode] = useState('');
const [city,setCity] = useState('');
const [state,setState] = useState('');
const API_URL = 'https://api.zip-codes.com/ZipCodesAPI.svc/1.0/QuickGetZipCodeDetails/';
const API_KEY = 'DEMOAPIKEY';
const updateZip = (e)=>{
e.preventDefault();
setZipcode(e.target.zipcode.value);
}
useEffect(()=>{
if (zipcode){
const loadAddressData = async ()=>{
const response = await fetch(`https://api.zip-codes.com/ZipCodesAPI.svc/1.0/QuickGetZipCodeDetails/?key=DEMOAPIKEY`);
const data = await response.json();
setCity(data.City);
setState(data.State);
}
loadAddressData();
}
},[zipcode]);
return (
<form onSubmit={updateZip}>
Zipcode: <input type="text" name="zipcode" />
<button type="submit">Lookup City/State</button><br />
City: {city}<br />
State: {state}<br />
</form>
)
}
export default ShippingAddress;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.