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


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


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() {
  this.state = {
    city: null,
    setCity: null,
    search: null,
    setSearch: z
  componentDidMount() {
   const fetchApi = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather? 
    const response = await fetch(url);
    const resJson = await response.json();
    this.setState({ setCity: resJson });
   render() {
   return (
          <div className="box">
          <div className="inputData">
             onChange={(event) => {
             var z= event.target.value;


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?