Reputation:
I'm trying to push the values in the input field to the firebase app. I have managed to fetch data from it but i can't seem to understand the submit function. I feel like i'm missing something really simple. When i try to use savePost it says it's not a function.
the action is:
export function savePost(post) {
return dispatch => database.push(post)
}
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { savePost } from '../actions/index';
class AddPost extends Component {
constructor(props) {
super(props);
this.state= {
title: '',
body: ''
}
this.onChangeTitle = this.onChangeTitle.bind(this)
this.onChangeBody = this.onChangeBody.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChangeTitle(e){
this.setState({
title: e.target.value,
})
}
onChangeBody(e){
this.setState({
body: e.target.value,
})
}
onSubmit(e, values) {
e.preventDefault();
savePost(this.state)
}
render() {
return (
<div className="container">
<form onSubmit={this.onSubmit.bind(this)}>
<input value={this.state.title} onChange={this.onChangeTitle} type="text" name="title" />
<input value={this.state.body} onChange={this.onChangeBody} type="text" name="body"/>
<button type="submit">Post</button>
</form>
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
savePost: dispatch(savePost())
});
export default connect(undefined, mapDispatchToProps)(AddPost);
Upvotes: 1
Views: 403
Reputation: 459
Change it to
const mapDispatchToProps = dispatch => ({
savePost: foo => dispatch(savePost(foo))
});
and in the function, it should be this.props.savePost(this.state.foo)
Upvotes: 0
Reputation:
It kinda worked when i changed the mapDispatchToProps to:
const mapDispatchToProps = () => {
return {
savePost: savePost
};
};
Upvotes: 1
Reputation: 5279
Within your onSubmit(e, values)
function, you are calling savePost(this.state)
which is actually calling the function you have imported at the top of the file.
The following code adds the function to the props of the component:
const mapDispatchToProps = dispatch => ({
savePost: dispatch(savePost())
});
So you need to do
onSubmit(e, values) {
e.preventDefault();
this.props.dispatch(savePost(this.state))
}
Upvotes: 0