0

I have successfully retrieved data from my API and set that data to setOfAllBooks state. I want to map the data in setOfAllBooks to a within the component. The page loads with the header alright but my data isn't there. I think there should be something wrong with mmy map() function.

import React, { Component } from 'react';
import './ViewAll.css';
import axios from 'axios'
const rootURL = 'http://localhost:5000';

const TableRow = ({ row }) => (
    <tr class="table-light">
        <th scope="row" key={row.title}>{row.title}</th>
        <td key={row.author}>{row.author}</td>
        <td key={row.isbn}>{row.isbn}</td>
        <td key={row.isbn}>24</td>
    </tr>
)

const Table = ({data}) => (
    <table class="table table-hover">
        <thead>
            <tr class="table-primary">
                <th scope="col">Title</th>
                <th scope="col">Author</th>
                <th scope="col">ISBN</th>
                <th scope="col">No. Of Copies</th>
            </tr>
        </thead>
        <tbody>
            {data.map(row => {
                <TableRow row={row} />
            })}
        </tbody>
    </table>

)
class ViewAll extends Component {
    constructor(props){
        super(props);

        this.state = {
            setOfAllBooks: []
        }
    }

    componentDidMount(){
        axios.get(`${rootURL}/api/book/viewAll`)
            .then(res => {
                this.setState({ setOfAllBooks: res.data });
                console.log(this.state.setOfAllBooks)
            })
    }

    render(){
        return(          
            <div>
                <Table data={this.state.setOfAllBooks} />       
            </div>
        )
    }
}

export default ViewAll;
0

1 Answer 1

4

You missed return inside the .map call.

{data.map(row => {
  // Missing return here. Add return, otherwise
  // callback function of the map returns undefined
  // which is the default return value of each functions
  // in JS
  <TableRow row={row} />
 // return <TableRow row={row} /> will fix it.

})}

Or write the implicit return version of the arrow function.

{data.map(row => <TableRow row={row} />)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.