Reputation: 55
I have been trying to find out but dunno what's going on. Even at React Tool, I can see the action is passed but the state is empty (for testing I have put the empty object at default). Action is passed but for some reason, the state is not returning as props. whatever I put at action, it's returning the default one which is empty.
//bookReducer
import { GET_BOOKS } from "../actions/types";
const initialState = {
books: [
{ id: 0, name: "Toten Tea", author: "Lonal" },
{ id: 1, name: "Poppy Hill", author: "Leonard" },
{ id: 2, name: "Clause Horse", author: "Henry Nicols" },
],
};
const bookReducer = (state = initialState, action) => {
// console.log(action.type);
switch (action.type) {
case GET_BOOKS:
return {
...state,
};
default:
return {};
}
};
export default bookReducer;
//Homepage
import React, { Component } from "react";
import { connect } from "react-redux";
import { GET_BOOKS } from "../actions/types";
class Homepage extends Component {
componentDidMount() {
this.props.dispatchAction();
}
render() {
const { books } = this.props;
// console.log(books);
console.log(this.props);
return (
<div>
<h1>Hello To Test-Redux Project</h1>
{books ? (
books.map((book) => {
return <li key={book.id}>{book.name}</li>;
})
) : (
<div>No Entry</div>
)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
books: state.books.books,
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatchAction: () => dispatch({ type: GET_BOOKS }),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Homepage);
Upvotes: 0
Views: 147
Reputation: 328
const mapStateToProps = (state) => {
return {
books: state.books.books,
};
};
Why state.books.books
only state.books
should do the job.
also this.props.dispatchAction();
is not changing any state.
Upvotes: 1