2

could you please help me, I add the ability to edit the date after adding. I get obj in TraningForm from TraningApp. I want to put this object into "useState", but for some reason this moment ignored. Although this object may be in the props, and I can get it safely:

enter image description here

Could you please explain to me what did I do wrong?

Code: https://github.com/tati-simonenko/22

1
  • Please paste code and image here. Links might break in future, and this won't be as useful for users coming in here Commented Jan 23, 2022 at 6:18

2 Answers 2

2

You pass the obj property as the initial state: useState(obj). Thus the form state is only set once.

const [form, setForm] = useState(obj);

Update the form state whenever the obj property changes.

const [form, setForm] = useState(obj);

useEffect(() => setForm(obj), [obj]);
Sign up to request clarification or add additional context in comments.

Comments

1

There were two issues in your code.

  1. In TraningForm form should be updated whenever obj changes. Need to add a useEffect hook below.
  useEffect(() => {
    setForm(obj);
  }, [obj]);
  1. In EditObj method there was a mistake. It should be ...item instead of ...prevTraining.
  const EditObj = (obj) => {
    setTraining((prevTraining) =>
      prevTraining.map((item) => {
        if (item.id == obj.id)
          return { ...item, date: obj.date, passed: obj.passed };
        return item;
      })
    );
  };

Code Sandbox

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.