IkeDoud
IkeDoud

Reputation: 87

Set state based on other objects in state?

So I'm trying to learn ReactJS by building a personal launch page. Sloppy explanation ahead.

Inside my main app.js file, I've initialized the state of the app with some info like so:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      links: {
        listA: ["CodeCademy","Udemy","StackOverflow","This is list A"],
        listB: ["ADSR","Youtube","Reddit", "This is list B"],
        listC: ["Overwatch", "R6S", "CSGO", "This is list C"],
        listD: ["Soundcloud", "Pandora", "Spotify", "This is list D"]
      },
      linkbar: {
        links1: "coding",
        links2: "chillin",
        links3: "vidya",
        links4: "music"
      },
      //activeList : something
    }; //etc

But for the life of me, I can't figure out if there's a way to base a property off of an existing property. In this case, I want to swap out the lists by referencing an activeList pair that references one of the this.state.links arrays. Any time I try to reference the arrays, however, results in an error saying activeList is undefined.

Am I missing something here? Is there a different way to approach this via a method that would do this appropriately? Is it possible to define activeList within the state or does this need to be done outside via a const? Appreciate any guidance, learning React is a bit rough for me here. Cheers!

Upvotes: 0

Views: 49

Answers (1)

user6198643
user6198643

Reputation:

The only way to interact with multiple levels inside the state, is to manipulate your objects outside the state then pass them in.

From what I see of your code, I'm not sure that playing with states for all this is the best idea. However here is an example.

myHandler() {
    var levelA = {...this.state.levelA};
    levelA.levelB = ["hello"];
    // so something
    this.setState(levelA);
}

Upvotes: 1

Related Questions