0

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')
      }

      ...

    }
user2052618
  • 556
  • 2
  • 7
  • 20

2 Answers2

1

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

Community
  • 1
  • 1
John Ruddell
  • 25,283
  • 6
  • 57
  • 86
0

You can do something like this:

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

or with Dynamic keys with ES6

setState({ [storeKey]: response });
Jonathan Dion
  • 1,651
  • 11
  • 16