Search code examples
javascriptarraysreactjsobjectsetstate

How to set state to an array of objects in react


I am working on a flash card react application. I have initialized my state as an array of objects (the user can only add up to 10 terms/definitions at a time so limited to 10) as follows:

state = { 
        allTerms: [
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        }
    ]
}

The input comes from a dynamic form that provides X number of input fields based on the number of cards the user wanted to add. My current problem is my onChange function. When a user types something in an input field (right now focused on the term and figure I can use a similar solution for definition) the change calls my onChangeTerm function where I have a for loop:

onChangeTerm = (event) => {

        for(var i = 0; i < this.props.numberOfTerms.length; i++) {
            this.setState({ allTerms[i].term: event.target.value});
        }
    }

I am having trouble with the setState line. My idea was that allTerms is my array that is in state. I want to set the value from the event (input from user) to the i element (increases as the for loop runs in the situation the user is wanting to add multiple cards) of the array, and specifically to the property of term in each object. However, I get a failed to compile error. Why is this setState line not working? My logic makes sense to me, but I seem to be missing something...is my syntax messed up? Or is there a piece the logic I am missing when it comes to setting state for an array of objects? Thanks for any ideas.


Solution

  • Here you go :

    You can pass event and index both to the function :

    Ref is taken from your prev question :

    <input type="text" name={i.term} placeholder="TERM" 
    value={this.state.allTerms[i].term} 
    onChange={(e) =>this.onChange(e,i)}> // <--- Change
    </input>
    

    Update something like this :

    onChangeTerm = (event , index) => {
        this.setState({
            allTerms : [
            ...this.state.allTerms.splice(0,index) ,
            {
                ...this.state.allTerms[index],
                term: event.target.value
            },
            ...this.state.allTerms.splice(index+1) ,
        });
    }