Home > database >  Declaration or statement expected when I try to declarate a previus state
Declaration or statement expected when I try to declarate a previus state

Time:05-20

I'm reading the react documentation, and I realized that I'm typing the syntax wrong when trying to change the state in react

So I am trying to change this to the correct form but it gives me an error

Old version

function handleInputChange() {
  setState({...state, [e.target.name]: e.target.value,
  });
}

New version

function handleInputChange() {
  setState((prev_state)=>{...prev_state,[e.target.name]: e.target.value});
}

Declaration or statement expected.

CodePudding user response:

You forgot to include 'e' as the parameter

function handleInputChange(e) {
   setState((prev_state)=>{...prev_state,[e.target.name]: e.target.value});
}

CodePudding user response:

in order to return an object using the arrow function syntax you just have to wrap it with additional rounded brackets :) so you code should look like:

function handleInputChange(e) {
  setState((prev_state)=>({...prev_state,[e.target.name]: e.target.value}));
}

or of course with the old syntax it can look like:

function handleInputChange(e) {
  setState(function(prev_state){
    return {...prev_state,[e.target.name]: e.target.value}
  }
);
}
  • Related