Listing 11-17: useZipLookup: a custom hook to return location data based on a zipcode
import {useEffect,useState} from 'react';
function useZipLookup(zipcode){
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';
useEffect(()=>{
if (zipcode){
const loadAddressData = async ()=>{
const response = await fetch(`${API_URL}${zipcode}?key=${API_KEY}`);
const data = await response.json();
setCity(data.City);
setState(data.State);
}
loadAddressData();
}
},[zipcode]);
return [city,state];
}
export default useZipLookup;
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.