Home > Enterprise >  useState won't render a page
useState won't render a page

Time:11-23

I am trying to rewrite the CV React app so that it uses Hooks. I have this code below:

const App = () => {
  const [values, setValues] = useState({
    name: "",
    email: "",
    phone: "",

    schoolName: "",
    studyTitle: "",
    completion: "",
    studyStartDate: "",
    studyEndDate: "",

    companyName: "",
    positionTitle: "",
    mainTasks: "",

    isFormSaved: false,
    btnText: "Save info"
  });

  const handleButtonClick = () => {
    setValues({
      isFormSaved: !values.isFormSaved
    });

    if (!values.isFormSaved) {
      setValues({ btnText: "Edit info" });
    } else {
      setValues({ btnText: "Save info" });
    }
  };

  const handleChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  const overview = (
    <section className="overview">
      <Overview data={values} />
    </section>
  );

  const form = (
    <section className="editInfo">
      <GeneralInfo
        onChange={handleChange}
        disabled={values.isFormSaved}
        placeholder={values}
      />
      <Experience
        onChange={handleChange}
        disabled={values.isFormSaved}
        placeholder={values}
      />
      <Practice
        onChange={handleChange}
        disabled={values.isFormSaved}
        placeholder={values}
      />
    </section>
  );

  return (
    <div className="app">
      <h1>CV Application</h1>
      {values.isFormSaved ? overview : form}
      <button onClick={handleButtonClick}>{values.btnText}</button>
    </div>
  );
};

export default App;

I have trouble woth the page rendering. The button works but the desired effect - rendering of the preview site is not working. I suspect the fault lies in the App.js code above.

Thank you in advance for any help.

CodePudding user response:

You are currently overwriting all values when changing the button text. You are probably just translating your react component code to hooks too literally. useEffect doesn't work exactly the same as setState, it always writes the entire value, because it's meant for state variables, not for the entire state.

It's easy to fix though:

    if (!values.isFormSaved) {
      setValues(values => ({ ...values, btnText: "Edit info" }));
    } else {
      setValues(values => ({ ...values, btnText: "Save info" }));
    }
  • Related