Polisas Polisas - 16 days ago 11
React JSX Question

React Geosuggest doesn't update state

i'm trying to make a weather app, and using external component 'react-geosuggest'.

My problem is, when I update the input (SEE:onChange={this.onInputChange}), that function doesn't take my input, and don't change the state, i.e I get undefined.

What's interesting, i've set initialvalue to be New York, and on submit I get results, without changing input information, so problem lies in updating input information and passing it to function handleOnSubmit.

I've read docs about that component, but couldn't figure it out, it has same values as simple , but something doesn't work.

Thanks!

class SearchBar extends Component {
constructor() {
super()

this.state = {city: 'New York'};
}

onInputChange = (e) => {
this.setState({city: e.target.value});
}

handleOnSubmit = (e) => {
e.preventDefault();
this.props.fetchWeather(this.state.city);
this.setState({city: ''});
}

render () {
return (
<div>
<form onSubmit={this.handleOnSubmit}>
<Geosuggest
initialValue={this.state.city}
onChange={this.onInputChange}
types={['(cities)']}
/>
<button type="submit">Search</button>
</form>
</div>
</div>
);
}
}

Dez Dez
Answer

Bind the event on the constructor, set the value attribute in the render and remove the setState to empty string that you are doing in the handleOnSubmit event. I am afraid this last one is what it makes not working when you change the input.

class SearchBar extends Component {
        constructor(props) {
          super(props);
          this.state = {city: 'New York'};
          this.onInputChange = this.onInputChange.bind(this);
        }

        onInputChange = (city) => {
            this.setState({city: city});
        }

        handleOnSubmit = (e) => {
             e.preventDefault();
             this.props.fetchWeather(this.state.city);
        }

        render () {
          return (
            <div>
                <form onSubmit={this.handleOnSubmit}>
                  <Geosuggest
                    initialValue={this.state.city}
                    value={this.state.city}
                    onChange={this.onInputChange}
                    types={['(cities)']}
                />
             <button type="submit">Search</button>
            </form>
          </div>
        </div>
       );
      }
    }
Comments