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.