I found this tutorial article about creating MERN project https://medium.com/swlh/how-to-create-your-first-mern-mongodb-express-js-react-js-and-node-js-stack-7e8b20463e66. All is working fine, but what I'm confused with this code inside componentDidMount()
function in MoviesList.jsx file:
import React, { Component } from 'react'
import ReactTable from 'react-table'
import api from '../api'
import styled from 'styled-components'
import 'react-table/react-table.css'
const Wrapper = styled.div`
padding: 0 40px 40px 40px;
`
class MoviesList extends Component {
constructor(props) {
super(props)
this.state = {
movies: [],
columns: [],
isLoading: false,
}
}
componentDidMount = async () => {
this.setState({ isLoading: true })
await api.getAllMovies().then(movies => {
this.setState({
movies: movies.data.data,
isLoading: false,
})
})
}
render() {
const { movies, isLoading } = this.state
console.log('TCL: MoviesList -> render -> movies', movies)
const columns = [
{
Header: 'ID',
accessor: '_id',
filterable: true,
},
{
Header: 'Name',
accessor: 'name',
filterable: true,
},
{
Header: 'Rating',
accessor: 'rating',
filterable: true,
},
{
Header: 'Time',
accessor: 'time',
Cell: props => <span>{props.value.join(' / ')}</span>,
},
]
let showTable = true
if (!movies.length) {
showTable = false
}
return (
<Wrapper>
{showTable && (
<ReactTable
data={movies}
columns={columns}
loading={isLoading}
defaultPageSize={10}
showPageSizeOptions={true}
minRows={0}
/>
)}
</Wrapper>
)
}
}
export default MoviesList
Why we have to set the isLoading: true in this code this.setState({ isLoading: true })
, then set it back to false with this code :
await api.getAllMovies().then(movies => {
this.setState({
movies: movies.data.data,
isLoading: false,
})
})
I've been struggling with this question for almost a week. I really need help in understanding this code. Thank you in advance.
You need to somehow show the user that page is loading data and data hasn't been loaded yet. ReactTable
has a property for this (loading
and I think it also has loadingText
too to display a message while loading/fetching data), so when you load your page, isLoading
is set to true
When your async/await
code finishes and data is fetched from url, the isLoading
is set to false
and ReactTable
is updated accordingly.