From 17c4b693665c82eb4af7f119e72578c1b69f9e96 Mon Sep 17 00:00:00 2001 From: Xiuwen Zhu Date: Tue, 8 Oct 2024 19:22:21 -0400 Subject: [PATCH] completed API lab --- src/App.jsx | 62 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 6478b09..1f54c64 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,25 +1,75 @@ -import { useState } from "react"; +import { useState, useEffect } from "react"; import "./App.css"; function City(props) { - return
This is the City component
; + return ( +
+
{props.city.City}, {props.city.State}
+ +
+ ); } function ZipSearchField(props) { - return
This is the ZipSearchField component
; + return ( +
+

Zip Code

+ +
+ ); } function App() { + const [zip, setZip] = useState(""); + const [data, setData] = useState([]); + + const ZipSearchHandler = (e) => { + const value = e.target.value; + + if (value.length === 5) { + setZip(value); // Set zip code when length is exactly 5 + } else { + setData([]); // Clear data if the zip code is not valid + } + } + + const DataFetcher = async () => { + if (zip.length !== 5) return; + + try { + const response = await fetch(`https://ctp-zip-code-api.onrender.com/zip/${zip}`); + const data = await response.json(); + setData(data); + } catch (error) { + console.error(error); + setData([]); // Clear data if the fetch fails + } + } + + useEffect(() => { + if (zip.length === 5) { + DataFetcher(); + } + }, [zip]); + return (

Zip Code Search

- +
- - + {data.length > 0 ? ( + data.map((city, index) => ) + ) : ( + No results found + )}