0

I don't even know the name for this, hence the title.

I basically initialize my modal form by either loading the data passed via props (for editing) or loading an empty struct (to create new entries):

defaultStruct: {
    text: null,
    active: true,
    options: [
        {
            text: null,
            correct: true,
            position: 0,
            _destroy: false,
        }
    ]
},
getInitialState() {
    return {
        question: this.props.initialQuestion == null ? this.defaultStruct : this.props.initialQuestion,
    };
}

The main idea is to reset the form using this.defaultStruct again, after submitting the form.

But, when I do a console.log(this.defaultStruct) after submit, I can see that it has actually been populated with data from the form's state. So... what the hell.

handleSubmit(e){
    if(e){e.preventDefault();}
    $.ajax({
        url: this.state.question.id == null ? this.props.applicationData.routes.questionsCreate : this.props.applicationData.routes.questionsUpdate,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        data: this.digestDataForStupidRails('question', 'options'),
        success: function(data) {
            console.log(this.defaultStruct)
        }.bind(this),
        error: function(xhr, status, err) {

        }.bind(this)
    });
}

Console output:

{
    "question": {
        "text": "preg 1",
        "active": true,
        "options": [
            {
                "text": "preg 1 a 1",
                "correct": false,
                "position": 0,
                "_destroy": false
            },
            {
                "text": "preg 1 a 2",
                "correct": true,
                "position": 1,
                "_destroy": false
            }
        ]
    }
}

Of course I can solve this by using a function instead, and make it return an empty struct each time, but this keeps me curious nevertheless.

Can anybody explain this behavior?

Alfredo Re
  • 122
  • 7

1 Answers1

2

This is not specific to React, it's how javascript (or basically any similar language) works. The defaultStruct is an object, therefore it's passed by reference, not as a new copy. If you want to keep the getInitialState, you should find a way to clone the object, either by what's suggested in the liked answers or by using a library which already has this functionallity, for example lodash, underscore or similar. Or, since you're already using jquery, you can use $.extend, as answered in second answer of the first link.

Community
  • 1
  • 1
Marko Gresak
  • 7,950
  • 5
  • 40
  • 46