I'm attempting to make a simple app that takes in a zip code text value from an input, and once a button is clicked passes that zip code into the URL string of the get request, and get the data/console.log it.
When I run the app it immediately fires the API request without the chance to pass the zipcode into the query string and does an infinite loop of requests. Any help on what the fix for this problem is would be appreciated. Here is the code for the component.
import React, { useState } from "react"; import { Form, Button } from "react-bootstrap"; import env from "react-dotenv"; import "./zipform.css"; const ZipForm = () => { const [zipcode, setZipcode] = useState(""); const [data, setData] = useState(null); let url = `api.openweathermap.org/data/2.5/weather?zip=${zipcode},us&appid=${env.API_KEY}` const fetchRequest = () => { fetch(url) .then(response => setData(response)) .then(console.log(data)); } return ( <div> <Form className="bg-light rounded p-3" id="form"> <h1 className="app-label">Get Me Something</h1> <div className="data"></div> <Form.Group controlId="formBasicEmail"> <Form.Label>Zip Code</Form.Label> <Form.Control type="text" placeholder="Enter Zipcode" className="form-input" onChange={e => setZipcode(e.target.value)} /> </Form.Group> <Button variant="primary" type="submit" onClick={fetchRequest()} > Submit </Button> </Form> </div> ); }; export default ZipForm;
https://stackoverflow.com/questions/65802197/react-component-fires-endless-api-requests-onload January 20, 2021 at 10:21AM
没有评论:
发表评论