I am struggling with a situation where I need to grab the value of an input field to make an API call.
So What I have is this:
import React, { Component } from 'react'
import axios from 'axios';
const fetchWeather = function (e) {
e.preventDefault();
axios.get('https://api.openweathermap.org/data/2.5/weather?q=Zeist&appid=MYID')
.then(res => {
console.log(res.data);
});
console.log();
}
export default class App extends Component {
render() {
return (
<div>
<form onSubmit = {fetchWeather}>
<input type = 'text' placeholder = 'Your city' ref="city"></input>
<input type = 'submit' placeholder='Submit' value = 'Submit'></input>
</form>
</div>
);
}
}
A form that runs a function on submit, I used preventDefault to stop the page from loading.
The function runs and the page doesn't reload. Now I'd like to grab the text from the input field and log it in that function. The reason why I want this is so I can use it in my API call as a query parameter. I tried many things. I tried logging e to see what is inside. It's a very big object and I couldn't find the value I'm looking for. I tried using ref, this didn't work either. Any idea how I could solve this issue?
value=andonChange=on the ipunt. That way, you'll be able to definefetchWeatheras a method inside your component and have access to the state object there.