Home > Mobile >  Can not excess the value of a variable outside the class
Can not excess the value of a variable outside the class

Time:12-18

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>
    );
  }
}

CodePudding user response:

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 :

const apikey = "zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD";

export default class WeatherForm extends React.Component {
  constructor(props) {
    super(props);
    
    this.handleLocationChanged = this.handleLocationChanged.bind(this);
    this.state = {
      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() {
    console.log(this.state.location);
    if (this.state.location){
      this.getcity(this.state.location)
      .then((data) => {
        console.log(this.getweather(data.Key));
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => console.error(err));
    }
  }

  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];
  };

  render() {
    return (
      <div>
        <label>location:</label>
        <input type="text" onChange={this.handleLocationChanged} />
        <br />
        <hr />
        <button onClick={this.handleButtonClicked.bind(this)}>search</button>
      </div>
    );
  }
}

CodePudding user response:

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.

  • Related