Dandy
Dandy

Reputation: 1481

getInitialState() replacing existing state. How to pass existing state in React?

I'm making some buttons that will show a certain class depending on the status from the database.

I've passed my API results through an emitter and into my state using the below:

  constructor(props) {
    super(props);
    this.state = {
      tickets: [],
      user: []
    };
    this.onGetAllTickets = this.onGetAllTickets.bind(this);
    this.onGetCurrentUser = this.onGetCurrentUser.bind(this);
  }

However, I'm having to set a new state in my button using the getInitialState() option. My button looks like this:

const AssignButton = React.createClass({
  getInitialState() {
    return {
      isPressed: false,
      completeStatus: "Assign"
    };
  },
  handleClick() {
    this.setState({
      isPressed: true,
      completeStatus: "Assigned",
    });
  },
  render () {
    var assignClass =  'ui orange right floated button assign';

    //THIS IS WHERE I AM TRYING TO CHECK TICKET STATUS 
    if(this.state.tickets.status === 2) assignClass = 'ui green right floated button done disabled';
    else if(this.state.isPressed) assignClass += ' disabled';
    return <button className={assignClass} onClick={this.handleClick}>{this.state.completeStatus}</button>;
  }
});

However, passing the this.state.tickets.status results in the following:

TicketeesBoard.js:123 Uncaught (in promise) TypeError: Cannot read property 'status' of undefined(…)

I'm assuming this is because my state is overwritten by the getInitialState() method.

The this.state.tickets.status etc. works outside of this AssignButton component.

How do I pass my tickets from the original state into the getInitialState() method?

Upvotes: 0

Views: 161

Answers (1)

alexunder
alexunder

Reputation: 2155

The problem is that you're trying to access the state of a different component. Your'e addressing this.state.tickets.status where ticket state is not declared in AssignButton

You've got two components. TicketBoard & AssignButton. Your setting the tickets state in TicketBoard and you're trying to access it in AssignButton

Try passing down the tickets state to the assignButton via props and the change your conditions from this.state.tickets.status to this.props.tickets.status. In addition, make sure that you won't have problems with .status being called on an empty array...

Upvotes: 2

Related Questions