Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  49] [ 6]  / answers: 1 / hits: 31383  / 6 Years ago, sun, november 4, 2018, 12:00:00

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


More From » reactjs

 Answers
5

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.


[#53181] Tuesday, October 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;