Error: Cannot read property ‘map’ of undefined (state) inside render method

In my project I have a table from react material ui. I am getting an error while filling this table when I use data from state to fill the table. The error is cannot read property 'map' of undefined. The line where it occurs will be marked in the code snippet below.

Here is my code (the error is in the JSX render method):

class AllBooks extends React.Component {

    constructor(props) {

        this.state = {
          rows: []

    componentDidMount() {
        console.log('component mounted!');

        axios.get('http://localhost:8080/all-books').then(allBooks => {

                rows: allBooks


    onAddButtonClick = (row) => {
        console.log('onAddButton click!');
        //'http://localhost:8080/addBookToRentedBooks', { email:, 
title: this.state.title, message: this.state.message }).then();

    test = () => {
        console.log(; => console.log(row));

    render() {
        return (

                <Grid container spacing={3}>
                    <Grid item xs={6} sm={3}></Grid>
                    <Grid item xs={6} sm={6}>
                        <h1 style={{textAlign: 'center'}}>All Books</h1>
                        <br /><br />

                        <TableContainer component={Paper}>
                            <Table  aria-label="simple table">
                                        <TableCell >Title</TableCell>
                                        <TableCell align="right">Author</TableCell>
                                        <TableCell align="right">ISBN</TableCell>
                                        <TableCell align="right">Year</TableCell>
                                        <TableCell align="center">Actions</TableCell>

                                    { => (
                                        <TableRow key={}>
                                            <TableCell component="th" scope="row">
                                            <TableCell align="right">z</TableCell>
                                            <TableCell align="right">z</TableCell>
                                            <TableCell align="right">z</TableCell>
                                            <TableCell align="center">
                                                    <IconButton onClick={ () => this.onAddButtonClick(row) }>
                                                        <AddCircleOutlineIcon />


                    <Grid item xs={6} sm={3}><button onClick={this.test}>click me</button></Grid>


I wonder why is marked as undefined because I added a simple button – when i click this button, the test method gets called and prints out this.state.rows correctly.

What did I do wrong?

Thanks for every help!


Because initial of state rows is []. so when fetching data will be undefined.

You can use optional chaining to check it has value or not before using map: