Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
Changing a React State Object with Spread Operator

I'm trying to validate a form before submting it,and I created an object of possible errors, but when try to change the value of each key it behaves weirdly...

const inialState = {
  name: "",
  email: "",
  message: "",
};
const errors = {
  name: false,
  email: false,
  message: false,
};
const Contact = () => {
  const [values, setValues] = useState(inialState);
  const [error, setError] = useState(errors);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateSubmit()) {
      return;
    }
  };
  const handleChange = (e) =>
    setValues({ ...values, [e.target.name]: e.target.value });

  function validateSubmit(e) {
    let response = true;
    if (!values.name) {
      setError({ ...error, name: true });
      response = false;
    }
    if (!values.email) {
      setError({ ...error, email: true });
      response = false;
    }
    if (!values.message) {
      setError({ ...error, [errors.message]: true });// I also tried this way =(
      response = false;
    }
    console.log(error);
    return response;
  }
...
return(
    <form onSubmit={handleSubmit}> //its a simple button type="submit"
...

The validateSubmit function is called by the Submit button.

This is what It's shown when I submit the form and its supossed to change the state values...

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The answer here is useReducer() to modify only portions of the state. https://reactjs.org/docs/hooks-reference.html#usereducer.

const errors = {
     name: false,
     email: false,
     message: false,
};

const reducer = (state, action) => {
    return {...state, ...action};
};

const [error, updateError] = useReducer(reducer,
    errors
);

function validateSubmit(e) {
    let response = true;
    if (!values.name) {
      updateError({name: true });
      response = false;
    }
    if (!values.email) {
      updateError({email: true });
      response = false;
    }
    if (!values.message) {
      updateError({message: true });
      response = false;
    }
    return response;
}
about 4 years ago · Juan Pablo Isaza Report

0

The problem occurs when you call setError multiple times from validateSubmit. Only the last value will win - in your example that's the one that added "false": true (because errors.message that you used as a property name is false).

Notice that setError does not (synchronously, or at all) update the error constant, it only changes the component state and causes it to re-render with a new value. The {...errror, …} always did refer to the original value of error. To avoid this, you can

  • either aggregate the errors into a single value before calling setError once

    function validateSubmit(e) {
      let newError = error;
      if (!values.name) {
        newError = { ...newError, name: true };
      }
      if (!values.email) {
        newError = { ...newError, email: true };
      }
      if (!values.message) {
        newError = { ...newError, message: true };
      }
      console.log(error, newError);
      setError(newError);
      return newError != error;
    }
    
  • or use the callback version of setError that will execute the updates in a row and always pass the latest state in each callback as an argument:

    function validateSubmit(e) {
      let response = true;
      if (!values.name) {
        setError(oldError => ({ ...oldError, name: true }));
        response = false;
      }
      if (!values.email) {
        setError(oldError => ({ ...oldError, email: true }));
        response = false;
      }
      if (!values.message) {
        setError(oldError => ({ ...oldError, message: true }));
        response = false;
      }
      console.log(error);
      return response;
    }
    
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!