1

I have this code where it will show the temperature of a place using AccuWeather API. right now I have hardcoded newdelhi into it to find the weather condition of that place.but I want to know the weather by using the form. i am right know testing it with first name input form and trying to send that value in the location function. but I can't use the input given by the user and use it outside the class. need help. i am new in react and appreciate if someone could help me with it. thank you

import React ,{useState,useEffect,state}from 'react';
import './App.css';
const apikey='zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD';

const getcity = async(city) => {
  const base = 'http://dataservice.accuweather.com/locations/v1/cities/search';
  const query = `?apikey=${apikey}&q=${city}`;

  const response = await fetch(base + query);
  const data = await response.json();

  return data[0];
}

getcity('New Delhi')
.then(data => {
  return getweather(data.Key);
}).then(data =>{
  console.log(data);
})
.catch(err =>console.error(err));

const getweather = async(id)=>{

  const base= 'http://dataservice.accuweather.com/currentconditions/v1/';
  const query =`${id}?apikey=${apikey}`;

  const response = await fetch(base + query)
  const data = await response.json();

  return data[0];
}

let newval = "initial value";
console.log(newval)

export default class CustomerForm extends React.Component {  
  constructor(props) {
    super(props); 

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status,
        
      }
    } 
  }

  handleFirstNameChanged(event) {
    var customer        = this.state.customer;
    customer.firstName  = event.target.value;

    this.setState({ customer: customer });
  }

  handleLastNameChanged(event) {
    var customer      = this.state.customer;
    customer.lastName = event.target.value;

    this.setState({ customer: customer });
  }

  handleStatusChanged(event) {
    var customer    = this.state.customer;
    customer.status = event.target.value;
    this.setState({ customer: customer });
  }
  
  
  handleButtonClicked() {
    console.log(this.state.customer);
    newval=this.state.customer.firstName;
    console.log(newval);
  }
  
  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName} onChange={this.handleFirstNameChanged.bind(this)}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName} onChange={this.handleLastNameChanged.bind(this)}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status} onChange={this.handleStatusChanged.bind(this)}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
        <hr/>
        <button onClick={this.handleButtonClicked.bind(this)}>
          Save Record
        </button>
      </div>
    );
  }
}
HDM91
  • 1,318
  • 9
  • 16
red wing
  • 43
  • 9
  • Do you want to send request to accu weather when button would click? – HDM91 Dec 18 '21 at 10:10
  • i want to type a name of a location in firstname and use that location to find the weather of that place. right now I have console logged the result of new delhi since I have hard coded new delhi in the code but I want to give location name – red wing Dec 18 '21 at 10:20

2 Answers2

1

You just have to define your method inside your class and call them in button handler, before that you need to update state in input handle change, if you want store weather data in component state you can define another key in state for that and update it when weather data will received and show it in your component or pass it to another component

const apikey = "zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD";

getCity = async (city) => {
  const base = "http://dataservice.accuweather.com/locations/v1/cities/search";
  const query = `?apikey=${apikey}&q=${city}`;

  const response = await fetch(base + query);
  const data = await response.json();

  return data[0];
};

getWeather = async (id) => {
  const base = "http://dataservice.accuweather.com/currentconditions/v1/";
  const query = `${id}?apikey=${apikey}`;

  const response = await fetch(base + query);
  const data = await response.json();

  return data[0];
};

export default class WeatherForm extends React.Component {
  constructor(props) {
    super(props);

    this.handleLocationChanged = this.handleLocationChanged.bind(this);
    this.state = {
      weatherData: null,
      location: props.location,
    };
  }

  handleLocationChanged(event) {
    if (event.target.value) {
      this.setState((prevState) => ({
        ...prevState, //it's for the cases that use another state other than location
        location: event.target.value,
      }));
    }
  }

  handleButtonClicked() {
    const _this = this;

    if (this.state.location) {
      getCity(this.state.location)
        .then((data) => getWeather(data.Key))
        .then((data) => {
          _this.setState((prevState) => ({ ...prevState, weatherData: data }));
          //call backend api here with data from weather api
          console.log(data);
        })
        .catch((err) => console.error(err));
    }
  }

  render() {
    return (
      <div>
        <label>location:</label>
        <input type="text" onChange={this.handleLocationChanged} />
        <br />
        <hr />
        <button onClick={this.handleButtonClicked.bind(this)}>search</button>
        <p>{this.state.weatherData}</p>
      </div>
    );
  }
}
HDM91
  • 1,318
  • 9
  • 16
  • i couldn't understand the code totally. i am not getting the array data of weather conditions of any place that I type. where is the data for that being stored at? – red wing Dec 18 '21 at 13:51
  • you didnt say that you want to store weather data its just get weather data by location name and log it if you want to store it and show it in another component you have multiple choice if you say your requirment completly i would help you – HDM91 Dec 18 '21 at 13:55
  • my main requirement is to enter the location and be able to get the temperature of that place. i want to display those data in the componenet/screen and also be able to send that data to backend. thank you very much for helping me.means a lot – red wing Dec 18 '21 at 13:58
  • I've update the code , you can now see how to store the result from weather api and set it into component state – HDM91 Dec 18 '21 at 15:25
  • thank you very much. this worked. but now how do I access the value of the temperatures of that place? the file console logged is promise. and I need to go inside the object and the temperature inside that. – red wing Dec 18 '21 at 16:01
  • I didn't return it from first then – HDM91 Dec 18 '21 at 16:44
  • i am really sorry but it's not working – red wing Dec 19 '21 at 01:41
  • whats the error? – HDM91 Dec 19 '21 at 05:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240263/discussion-between-hdm91-and-red-wing). – HDM91 Dec 19 '21 at 06:30
0

In your handle change functions, you need to use the spread operator to update the state instead of just assigning a new value to it.

For instance, for handleFirstNameChanged try something like this:-

handleFirstNameChanged(event) {
 var customer = this.state.customer;
 customer.firstName  = event.target.value;
 this.setState({...this.state.customer,...customer });
}

This will update your state variable values. Refer to this for better understanding.

Akshay Mathur
  • 421
  • 4
  • 6