2
votes

I can't find out why i can't get the data, while I can access it through console.log() !

export class InnerTicket extends React.Component{
constructor(props){
    super(props);
    this.state = {
        ticket: ''
    }
}

componentDidMount() {
    this.getTicket().then(result => this.setState({
        ticket: result
    }))
}

getTicket(){
    const slug = this.props.match.params.id;
    return this.props.TicketsStore.loadTicket(slug);
}
render(){
    console.log(this.state);

everything works fine when I run this and i can see the data through the console:

{ticket: {…}}ticket: {success: true, data: {…}, error: "", message: ""}data: {result: "success", ticketid: 22, tid: "168552", c: "WHgCsCBO", deptid: 5, …}error: ""message: ""success: true__proto__: Object__proto__: Object

but when I want to display my data in the view like this:

render(){
    return( <span className="label label-warning">
                            {this.state.ticket.data.status}
                        </span>)

I get this error: TypeError: Cannot read property 'status' of undefined

2
what about render(){ return( <span className="label label-warning"> {this.state.ticket.data ? this.state.ticket.data.status : null} </span>) - ingvar
@ingvar the same error occurs... - Ali Jouadi
oops. {this.state.ticket ? this.state.ticket.data.status : null} should work - ingvar

2 Answers

2
votes

You're initialized your state to this:

this.state = {
    ticket: ''
}

So on the first render, this.state.ticket is an empty string, and this.state.ticket.data is undefined. Only later are you updating state.ticket to an object.

To fix this, either make the initial state be something that works with your render method, or make your render method check for the possibility of an empty string.

1
votes

I'm not sure if it's perfect, but should work fine:

render(){
    return( <span className="label label-warning">
                            {this.state.ticket.data.status ? this.state.ticket.data.status : null}
                        </span>)