I am trying to insert the value of my stateful variable (myValue) to the api url after q= I tried using ${} but it is not working. It is working when I insert text righ in to url, but I need to insert the input variable. ( sorry for messy code, I am a beginner )
p.s ignore the api key, I just replace it with *** here.
import React, { createRef } from "react";
import { Component } from "react";
import { Button, TextField } from "@mui/material";
import WeatherCard from './components/WeatherCard'
class App extends Component {
constructor(props) {
super(props);
this.textInput = createRef();
this.state = {
myValue: "",
temp : ""
};
}
showRefContent = () => {
this.setState({
myValue: this.textInput.current.value
});
const uriEncodedCity = encodeURIComponent(this.state.myValue);
fetch('https://api.openweathermap.org/data/2.5/weather?q=madrid&appid=***')
.then(response => response.json())
.then(data => this.setState({
temp : data.main.temp
}),
console.log(this.state.temp)
);
}
handleChange = (e) =>
this.setState({
myValue: e.target.value
});
render() {
return (
<div >
<div >
<TextField inputRef={this.textInput}
id="demo-helper-text-misaligned-no-helper" label="City name"
/>
<br></br>
<Button margin = "right:20" size="large" variant ="contained" onClick={this.showRefContent}>Get Weather</Button>
</div>
<p>
{this.state.myValue.length > 0
? <WeatherCard temp = {this.state.temp} />
: "no text"}
</p>
</div>
);
}
}
export default App;