I keep getting the error that my variable is not defined while trying to put var in this. state, here is my code
in this code the variable is supposed to get the input user has typed and update the set Search
class App extends React.Component {
constructor() {
super();
this.state = {
city: null,
setCity: null,
search: null,
setSearch: z
};
}
componentDidMount() {
const fetchApi = async () => {
const url = `https://api.openweathermap.org/data/2.5/weather?
q=${this.state.setSearch}&appid=f10cf2869c0
372186a094a41fc576f46`;
const response = await fetch(url);
const resJson = await response.json();
this.setState({ setCity: resJson });
};
fetchApi();
}
render() {
return (
<div>
<div className="box">
<div className="inputData">
<input
type="search"
className="inputField"
onChange={(event) => {
var z= event.target.value;
}}
/>
CodePudding user response:
You are declaring z only when the search input field change. Thus it doesn't exist yet when the contructor is called.
The correct way to do it in React would be to set the state.setSearch to "" in the constructor. Then in the search input onChange, call (event)=>this.setState({setSerch: event.target.value})