Silent-B
Silent-B

Reputation: 35

react axios State won`t set at first

i`m trying to get some data from an api.

class Article extends React.Component {
constructor() {
    super()
    this.state = {
        Articles: []
    }   
}
componentDidMount() {
    axios.get('/api/articles')
    .then(res => {
        this.setState({Articles: res.data})
    })
}
render() {
    return (
        <div className="container-fluid">
           {console.log(this.state.Articles)}
        </div>
    )
  }
}

My problem is when i try to get some data i get Errors like Undefined...

and thats because first time render runs the value is '[]' and after that the value updated.

How to solve this problem?

Upvotes: 0

Views: 41

Answers (2)

spaceSentinel
spaceSentinel

Reputation: 670

Just check if the articles array is empty and accordingly render the content :

class Article extends React.Component {
constructor() {
    super()
    this.state = {
        Articles: []
    }   
}
componentDidMount() {
    axios.get('/api/articles')
    .then(res => {
        this.setState({Articles: res.data})
    })
}
render() {
    return (
        <div className="container-fluid">
           {this.state.articles.length > 0 && console.log(this.state.articles)}
        </div>
    )
  }
}

The above code snippets checks to see if the articles array is of a length greater than 0 and if yes, it executes the statement in conjunction. You can do a lot of things with this property like displaying a loading spinner until your request completes and you can actually render the data.

Upvotes: 1

Dani
Dani

Reputation: 584

Set a basic demo value that will be in the array. This will immediately be replaced with the values of the API. You can use something like please wait, fetching data. If the user has a stable connection this demo value won't even be seen

Upvotes: 1

Related Questions