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

      ...

    }

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.