Skip to content
Advertisement

How to perform React state update after a form submission and API fetch

I have React class component called SearchLocationForm.js which is a child of App.js. Inside of the SearchLocationForm.js I have this code below

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
           error: null,
           isLoaded: false,
           coordinates: [] 
        }
        this.appid = this.props.appid;
    }

    handleSubmit(location) {

        fetch(
            `http://api.openweathermap.org/geo/1.0/direct?q=${location}&appid=${this.props.appid}`
        )
        .then(res => res.json())
        .then(resp => this.setState({coordinates: [resp.lat, resp.lon]}))
        .catch((error) => {
            console.error("there has been an issue with te GeoCode API Call", error)
        })

    }

    render() {
        return (
            <LocationInput className="searchLocationForm" handleSubmit={this.handleSubmit}/>
        )
    }

I am trying to figure out how I can use the setState() method to update the component state with the API response, and afterwards lift that up to the App.js component in order to make subsequent calls.

I have lookup many answers regarding this problem and have tried implementing many solutions but nothing seems to work as of now. What do you see going on within my code that seems to be causing the issue? Thanks!

Advertisement

Answer

If yiu want only the coordinate will update and other states will remains same you have to use spread operator like this way

handleSubmit(location) {
 
  fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${location}&appid=${this.props.appid}`)
      .then(res => res.json())
      .then(resp => this.setState({...thia.state, coordinates: [resp.lat, resp.lon]}))
      .catch((error) => {
          console.error("there has been an issue with te GeoCode API Call", error)
   })

}

And if you want to lift the state up to the app.js, you have to define the state on app.js and set the state from this component. Read more about lifting state up from here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement