1

I have declared a object in my state, se code:

this.state = {
  attendtext: "Attend",
  showPanel: false,
  attendespanel: null,
  user: this.user
};

I update it with the usual setState:

if (attenduser.isSiteAdmin) {
  this.setState(prevState => ({
    user: {
      ...prevState.user,
      isSiteAdmin: true
    }
  }));
}

But I cant access this objects properties. For example:

this.state.user.isSiteAdmin 

Above is not valid. How come?

My interface:

export interface UserItem {
  Key?: string;
  Username?: string;
  user?: {
    title: string,
    emailaddress: string,
    isSiteAdmin: boolean
  };
}

I also tried to set the state with:

this.state = {
  attendtext: "Attend",
  showPanel: false,
  attendespanel: null,
  user: { title: "", emailaddress: "", isSiteAdmin: false }
};

However, it gets red "Object literal may only specify known properties, and 'title' does not exist in type 'UserItem[]'" which happens for all the properties in the user object, even if they are declared in the interface.

dance2die
  • 31,758
  • 34
  • 122
  • 177
Arte2
  • 179
  • 13
  • Where are you using `this`? It may be doing [something you didn't know about](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – VLAZ Aug 13 '19 at 13:15
  • In a return function, inside the render. – Arte2 Aug 13 '19 at 13:17
  • You should try to bind "this", this may solve. For better explanation, please read @VLAZ URL. I also recommend reading this: https://stackoverflow.com/a/37833757/10473393 – Alexander Santos Aug 13 '19 at 13:24

1 Answers1

2

When you do,

this.state = {
  attendtext:"Attend",
  showPanel: false,
  attendespanel:null,
  //     
  user: this.user
}

this.use should be an instance variable of the component you are using this.state.
e.g.)

class App extends Component {
  user: {}
  constructor(props) {
    super(props)
    this.state = {...}
  }
}

But then, whenever App component re-renders, this.user is reset (back to the initial empty object, {}), as it won't be managed by React.

So more appropriate way to declare the state is to include the user as part of the this.state, which React can manage (CRUD with this.setState)

this.state = {
  attendtext: "Attend",
  showPanel: false,
  attendespanel: null,
  user: { isSiteAdmin: false }
};

Now you can access this.state.user.isSiteAdmin.

dance2die
  • 31,758
  • 34
  • 122
  • 177
  • Thanks for the input. Clarified it a bit. But my interface doesn't like it for some reasons (added it to my original post). – Arte2 Aug 13 '19 at 13:43
  • Would you also add code for how `this.state.user.isSiteAdmin` is being accessed? It seems like `UserItem[]` is an array of `UserItem` and doesn't match exactly with `this.state.user`. – dance2die Aug 13 '19 at 15:16