0

I'm doing react component. I have a common ajax call inside the funtion:

getPost = (postName, storage) => {
    this.setState({fetchInProgress: true})
    $.ajax({
       url: "/api/getitems",
       type: "GET",  
       dataType: 'json',  
       ContentType: 'application/json',
       data: {modelName: postName},
       success: (data) => {
         this.setState({
               storage: data,
               fetchInProgress: false
             })

       },  
       error: (jqXHR) => {
         this.setState({fetchInProgress: false})
         console.log('ERRORR')
       } 
    })
  }

I call it like this:

this.getPost('StandartPost', this.state.standartPosts)

but it doens't work. I have many different types of posts. For now I did this with switch:

  success: (data) => {
         switch(postName){ 
           case: 'StandartPost'
           this.setState({
               standartPosts: data,
               fetchInProgress: false
             })
           ...and so on
         }
       }

Here I'm not using the second parameter of my function. But also there is too much code. Is there a way to do it like this:

success: (data) => {
             this.setState({
                   storage: data,
                   fetchInProgress: false
                 })

           }

this.getPost('StandartPost', this.state.standartPosts)

UPD: I just tried to use this.state.something as a key inside this.setState method:

                 this.setState({
                   this.state.data: data,
                   fetchInProgress: false
                 })

well, it does nothing. this.state.data is still an empty array.

UPD2: I 've done the following in my ajax call:

success: (data) => {
         this.state[storage] = data
         this.setState({
           fetchInProgress: false
         })

and call the function getPost(postName, storage) like this:

this.getPost('StandartPost', 'standartPosts')

And it works fine. I dind't find a way to set the data inside setState method. But at least there is less code.

Dennis Braun
  • 259
  • 4
  • 15

1 Answers1

1

Do not modify state directly. You should only assign state directly in your constructor.

Using ES6, you can set use a variable as an object key by wrapping the variable in square brackets as follows:

this.setState({
  [storage]: data,
  fetchInProgress: false
});

If not, you could have created a new object, say newState, and passed that into setState:

success: (data) => {
  let newState = {
    fetchInProgress: false
  };  
  newState[storage] = data;
  this.setState(newState);
}
topher
  • 14,790
  • 7
  • 54
  • 70