Action does not trigger a reducer in React + Redux
As Rick Jolly mentioned in the comments on your question, your onSearchPressed()
function isn't actually dispatching that action, because addToSaved()
simply returns an action object - it doesn't dispatch anything.
If you want to dispatch actions from a component, you should use react-redux to connect your component(s) to redux. For example:
const { connect } = require('react-redux')
class MainView extends Component {
onSearchPressed() {
this.props.dispatchAddToSaved();
}
render() {...}
}
const mapDispatchToProps = (dispatch) => {
return {
dispatchAddToSaved: () => dispatch(addToSaved())
}
}
module.exports = connect(null, mapDispatchToProps)(MainView)
See the 'Usage With React' section of the Redux docs for more information.
Recently I faced issue like this and found that I had used action import but it has to come from props. Check out all uses of toggleAddContactModal. In my case I had missed toggleAddContactModal from destructuring statement which caused this issue.
import React from 'react'
import ReactDOM from 'react-dom'
import Modal from 'react-modal'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {
fetchContacts,
addContact,
toggleAddContactModal
} from '../../modules/contacts'
import ContactList from "../../components/contactList";
Modal.setAppElement('#root')
class Contacts extends React.Component {
componentDidMount(){
this.props.fetchContacts();
}
render(){
const {fetchContacts, isFetching, contacts,
error, isAdding, addContact, isRegisterModalOpen,
toggleAddContactModal} = this.props;
let firstName;
let lastName;
const handleAddContact = (e) => {
e.preventDefault();
if (!firstName.value.trim() || !lastName.value.trim()) {
return
}
addContact({ firstName : firstName.value, lastName: lastName.value});
};
return (
<div>
<h1>Contacts</h1>
<div>
<button onClick={fetchContacts} disabled={isFetching}>
Get contacts
</button>
<button onClick={toggleAddContactModal}>
Add contact
</button>
</div>
<Modal isOpen={isRegisterModalOpen} onRequestClose={toggleAddContactModal}>
<input type="text" name="firstName" placeholder="First name" ref={node =>
(firstName = node)} ></input>
<input type="text" name="lastName" placeholder="Last name" ref={node =>
(lastName = node)} ></input>
<button onClick={handleAddContact} disabled={isAdding}>
Save
</button>
</Modal>
<p>{error}</p>
<p>Total {contacts.length} contacts</p>
<div>
<ContactList contacts={contacts} />
</div>
</div>
);
}
}
const mapStateToProps = ({ contactInfo }) => {
console.log(contactInfo)
return ({
isAdding: contactInfo.isAdding,
error: contactInfo.error,
contacts: contactInfo.contacts,
isFetching: contactInfo.isFetching,
isRegisterModalOpen: contactInfo.isRegisterModalOpen
});
}
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
fetchContacts,
addContact,
toggleAddContactModal
},
dispatch
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(Contacts)