reactJS rendering empty data

Clash Royale CLAN TAG#URR8PPPreactJS rendering empty data
When I am fetching the data I want them to fetch first and then render. It always renders empty string even when I'm setting the state and I don't understand why.
class App extends React.Component {
constructor () {
super()
this.state = {
view: 'feed',
posts: '' //data I want to render
}
this.changeView = this.changeView.bind(this)
}
componentDidMount () {
this.getAllPosts() //getting the data
}
getAllPosts () {
axios.get('/api/blogs')
.then((response) => {
console.log(response)
this.setState({
posts: response
})
})
.catch((error) => {
console.log(error)
})
}
changeView(option) {
this.setState({
view: option
})
}
renderView () {
const {view} = this.state
if (view === 'feed') {
return <Feed blogs={this.state.posts} handleClick={() =>
this.changeView('anypostview')}/> //passing data as props in Feed blogs
} else {
return <Post />
}
}
render() {
return (
<div>
<div className="nav">
<span className="logo"
onClick={() => this.changeView('feed')}>
BLOGMODO
</span>
<span className={this.state.view === 'feed'
? 'nav-selected'
: 'nav-unselected'}
onClick={() => this.changeView('feed')}>
See all Posts
</span>
<span className="nav-unselected">
Write a Post
</span>
<span className="nav-unselected">
Admin
</span>
</div>
<div className="main">
{this.renderView()}
</div>
</div>
);
}
}
When I'm loging the data in my Feed component I first see an empty string and then it logs the fetched data. How can I prevent it from rendering an empty string and waiting for data to be fetched first and then rendering it?
A component can't delay its own rendering. If the component is the top level component you need to fetch the data first and only then render the react DOM. If it is a child the parent component needs to fetch first and only render the child when the data is available. The alternative is to indicate loading (e.g. a spinner) while the request did not finish.
– trixn
17 mins ago
I tried it with an array but would get the same problem.
– Lukas Luke Stateczny
12 mins ago
1 Answer
1
Within render, check if posts state is populate or not.
If not, show a loading screen or gif.
render
posts
When posts is populated, and then you will see rendered posts.
posts
render() {
const {posts} = this.state;
if (!posts || posts.length <= 0) {
// Display a message or Show a Loading Gif here
return <div>Loading...</div>
}
return (
<div>
<div className="nav">
...
</div>
<div className="main">
{this.renderView()}
</div>
</div>
);
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Just check if it's an empty string and return null? I would actually set the initial state to an array for consistency and check length.
– Li357
21 mins ago