0

I have a object from another component and I want to add objects value to my Data but when I click on submit first time the console.log show empty And next time it's okay. How can I do setState first?

    const postForm = ({addPost}) => {

    const [formData, setFormData] = useState({
        title: '',
        description: '',
        options: {}
    });


    const {
        title,
        description,
        options
    } = formData;

    const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });


    const onSubmit = e => {
        e.preventDefault();
        const oto = { ...options, ...newOptions }

        // >>  first time Not Work
        setFormData({ ...formData, options: oto })
        console.log(formData.options)
    }
MaK
  • 121
  • 1
  • 8

1 Answers1

0

The problem was solved by using an submitState in useEffect. By specifying a condition in the useEffect

    const [startOnSubmit, changeOnSubmit] = useState(false)

    useEffect(() => {
        if (startOnSubmit) {
            addPost(formData);
            changeOnSubmit(false);
        }
    }, [formData, addPost, startOnSubmit, changeOnSubmit]);

    const onSubmit = e => {
        e.preventDefault();
        const oto = { ...options, ...newOptions }
        setFormData({
            ...formData,
            options: oto,
            category: selected === null ? '' : selected.id
        });
        changeOnSubmit(true)
    }
MaK
  • 121
  • 1
  • 8