I am trying to push a React component into a javascript array. I am expecting the values in that array to be what the React component returns. Instead of that I get an array containing objects of like this: $$typeof: Symbol(react.element)...
.
Here is my code: loads books from an API when button is clicked and appends then to list of books already displayed (basically infinite scrolling):
Books:
function Books({ page }) {
const fetcher = url => api.get(url).then(response => response.data);
const { data: books } = useSWR(
`/books?page=${page}`,
fetcher
);
return books ? (
<>
{books.map(book => (
<Book key={book.id} book={book} />
))}
</>
) : null;
}
IndexPage:
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = { pages: 1 };
}
load = () => {
this.setState({ pages: this.state.pages + 1 });
};
render() {
const books = [];
for (let page = 1; page <= this.state.pages; page++)
books.push(<Books page={page} key={page} />);
console.log(books) // logs `$$typeof: Symbol(react.element)...` instead of `[null]`.
return (
<>
{books.length ? (
books
) : (
// This never executes because `books.length` is never zero
<li>No books yet.</li>
)}
<button onClick={this.load}>Load More Books</button>
</>
);
}
}
My goal is to find a way to display <li>No books yet.</li>
in the code below but I cannot find a way to do it dealing with the values I find in the array. Right now, if there are no objects I just see a blank page.
How can I make sure that the React component actual return values are stored in my array instead of these "symbol" objects?