user2052618
user2052618

Reputation: 616

Reactjs Set State Dynamic Key Javascript

i am having trouble with this one thing in my reactjs code but it is more of a problem of my understanding of how the javascript key/value array works as much as anything. how do i allow the key to be dynamically passed-in in the example below?

the details of the problem are in the done() function. any syntax errors are because i work on an intranet and had to hand type everything. as noted in the done() function, everything works if i hard code the key but i don't want that, of course. i've tried with and without quotes around the key.

  class Container extends React.Component {
      constructor(props){
        super(props)
        this.state = { 'abc': {}
        }

        this.retrieveDataFromTo = this.retrieveDataFromTo.bind(this)
      }

      retrieveDataFromTo(url, storeKey){
        $.ajax({
          method: 'GET',
          url:url,
          dataType: 'json'
        })
        .done(response => {
          this.setState({storeKey: response})
          //everything works if i do this instead of the above line...
          //this.setState({'abc': response})
          //which proves the only problem is the storeKey being "dynamic"
          //so how do i get the store key to work "dynamically" here?
         })
        .fail(ajaxError)
      }

      componentDidMount(){
        this.retreiveDataFromTo('abc/getData', 'abc')
      }

      ...

    }

Upvotes: 0

Views: 2324

Answers (2)

Jonathan Dion
Jonathan Dion

Reputation: 1671

You can do something like this:

this.setState(function(prevState){
  prevState[storeKey] = response;
  return prevState;
}))

or with Dynamic keys with ES6

setState({ [storeKey]: response });

Upvotes: 0

John Ruddell
John Ruddell

Reputation: 25842

Dynamic keys in ES6 Javascript are generally denoted with brackets around a variable storing the value of the key you want to change. So in your case you would want to do:

setState({ [storeKey]: response });

More on dynamic keys in JS

Upvotes: 1

Related Questions