Jevon Cochran
Jevon Cochran

Reputation: 1774

updating state through form inputs

I've built a flash card app to help with retaining programming concepts. By clicking buttons, the user can flip the "flash card" to see if they guessed the concept correctly and/or move on to the next card. There is also a button that allows the user to essentially, add a new flash card.

Upon clicking the add button, the user is taken to a form page where they can enter a new programming concept that they need to memorize along with its definition/explanation. Upon submitting, this form, the array being drawn from to produce the flash cards should update with this new input from the user. However, this is not happening right away. Currently, on submit, the form seems to be storing the user input somehow but that info only gets added to the appropriate array upon a second click. Can someone help me fix this problem? I've added a screen shot of the console to demonstrate what I mean.

enter image description here

The first click logs an array with 12 items, which is the length of the array in state. It should have added the user input to the array and logged 13 items. When I click again, it logs 13 items, showing that the array has been updated in state.

Here is the code for the form component:

const AddForm = props => {
    // console.log(props.stateConceptArray);
    const [newConcept, setNewConcept] = useState({ term: '', definition: '' });

    const handleChanges = e => {
       setNewConcept({
           ...newConcept,
           [e.target.name]: e.target.value
       });
       console.log(newConcept);
    }

    const handleSubmit = (e, obj) => {
        e.preventDefault();
        props.setStateConceptArray([
            ...props.stateConceptArray,
            obj
        ]);
        document.addForm.reset();
        console.log(props.stateConceptArray);
    }

    return (

        <form name="addForm" onSubmit={e => handleSubmit(e, newConcept)}>
            <label> New Term: <input type="text" name="term" placeholder="add new term" onChange={handleChanges} /></label>
            <br />
            <label>New Defintion: <input type="text" name="definition" placeholder="add new definition" onChange={handleChanges} /></label>
            <br />
            <button type="submit">Add</button>
        </form>
    )
}

export default AddForm;

Upvotes: 0

Views: 143

Answers (1)

rotemls98
rotemls98

Reputation: 187

setState is asynchronous so state doesnt update immedialty, but also props are immutable in react so they can never change. if you want to log to new array you could use the useEffect function.

const { stateConceptArray } = props;
useEffect(() => {
   console.log(stateConceptArray);
}, [stateConceptArray]);

Upvotes: 1

Related Questions