[SOLVED] ReactJS how to add variable in a constructor state in class

Issue

This Content is from Stack Overflow. Question asked by MoeezMahmood Ramay

I keep getting the error that my variable is not defined while trying to put var in this. state, here is my code

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;
            }}   
           />



Solution

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})


This Question was asked in StackOverflow by MoeezMahmood Ramay and Answered by user3252327 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?