Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

reactjs - How do I call the API?

How do I fix this?

import React from 'react';

function Form() {
    function callWeatherAPI(city) {
        let url = `api.openweathermap.org/data/2.5/weather?q=${city},&appid=3921214e64bf19a2ed23b79c5b270300`;
    }


    function submitForm() {
        // debugger;

        let city = document.forms["myForm"]["city"].value;
        let isValid = validateForm(city);
        if (isValid) {
            // call api
            callWeatherAPI(city);
        } else {
            alert("Please put in value for city");
        }
    }


    function validateForm(city) {
        if (city === "") {
            return false;
        } else {
            return true;
        }
        // return (city === "") ? false : true;
    }


    return ( <
        form name = "myForm"
        onSubmit = {
            submitForm
        } >
        <
        label > City: < /label> <
        input type = "text"
        name = "city" > < /input> <
        input type = "submit" > < /input>   <
        /form>

    );

}


export default Form;
question from:https://stackoverflow.com/questions/65925701/how-do-i-call-the-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to fetch the data from that endpoint, using fetch and the following approach could help:

function Form(){
  const [targetValue, setTargetValue] = useState('');

  async function callWeatherAPI(city){
    const response = await fetch(`endpoint/${city}`);
    return await response.json(); // You will probably receive an object, get the value you want and return it here
  }

  async function submitForm() {
    // You should get the form value using reactivity..
    const city = document.forms["myForm"]["city"].value;
    const isValid = validateForm(city);
    if (isValid) {
      const response = await callWeatherAPI(city);
      setTargetValue(response);
    } else {
      alert("Please put in value for city");
    }
  }

  return (
    <form name="myForm" onSubmit={submitForm}>
      <label>City:</label>
      <input type="text" name="city"></input>
      <input type="submit"></input>
      <p>Response: {targetValue}</p>
    </form>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...