Search code examples
arraysreactjsstate

Fill state property after ajax request


I've got an issue with React.js. I want to add another property (productGroups) to an existing state (this.state.mainProductGroups - type object array). So I want to find out the corresponding entry in the array and add the new property to it.

This is my function:

getProductGroups(mainProductGroupId) {
    $.ajax({
        type: "POST",
        context:this,
        dataType: "json",
        async: true,
        url: "ajax.php",
        data: ({ 
            requestType: 'getProductGroups',
            countryID: this.state.countryObject.countryNo,
            languageID: Language[this.state.currentLanguage].languageNo,
            mainProductGroupID: mainProductGroupId,
        }),
        success: function (data) {
           let mainProductGroups = this.state.mainProductGroups;
           let mainPGFound = false;
           let mainPG = mainProductGroups.filter(mainProductGroup => mainProductGroup.id == mainProductGroupId);
           mainPG.productGroups = data.productGroups;
           this.setState({
              mainProductGroups: mainProductGroups,
           });
           
        }
    });
  }

Here is an data example of the this.state.mainProductGroups:

enter image description here

The issue is now, that the productsGroup property is not being filled. The ajax request returns correct values (also type object array). Why is it not being updated? Is there a problem, because the initial value of the property productGroups is string and now I want to overwrite this with a type of object array?


Solution

  • My final solution is this one.

    getProductGroups(mainProductGroupId) {
        $.ajax({
            type: "POST",
            context:this,
            dataType: "json",
            async: true,
            url: "ajax.php",
            data: ({ 
                requestType: 'getProductGroups',
                countryID: this.state.countryObject.countryNo,
                languageID: Language[this.state.currentLanguage].languageNo,
                mainProductGroupID: mainProductGroupId,
            }),
            success: (data) => {
              let mainProductGroups = this.state.mainProductGroups.map((mainProductGroup) => {
                if(mainProductGroup.id === mainProductGroupId) {
                  mainProductGroup.productGroups = data.productGroups;
                }
                return mainProductGroup;
              });
              this.setState({
                 mainProductGroups: mainProductGroups,
              });
            }
        });
      }
    

    I think, the reason was that I did not change the state property mainProductGroups at all in my first solution. Now it is working fine. Thanks all for your help.