Reputation: 23
I'm dispatching an action from a component, everything looks like it's linked properly but when I console.log the state in my component props it has not updated.
I have tried reformatting my code and looked at multiple examples, and it looks like it's supposed to run? When I log from the reducer it's receiving the action it's just not updating the state.
const mapStateToProps = state => ({
todos: state
});
onSubmit(e) {
e.preventDefault();
let payload = this.state.content
this.props.dispatch(post_todo(payload));
console.log(this.props.todos)
this.setState({
content: ""
})
}
export default (
state = [],
action
) => {
switch (action.type) {
case POST_TODO:
console.log("got it")
console.log(action.payload)
console.log(state)
return [
...state,
action.payload
];
default:
return state;
}
};
export function post_todo (payload){
return {
type: POST_TODO,
payload
};
}
It should update the props.todos to the proper state but its showing an empty array everytime.
Upvotes: 2
Views: 6191
Reputation: 451
You can access the store from the component immediately as It'll contain the new value which hasn't made it yet to the component
import store from "../../redux/configureStore"
const requiredState = store.getState()[path of the required value];
I'm not sure if this is an anti-pattern though.
Upvotes: 0
Reputation: 6742
onSubmit(e) {
e.preventDefault();
let payload = this.state.content
this.props.dispatch(post_todo(payload)); <=== this line
console.log(this.props.todos)
this.setState({
content: ""
})
}
when you dispatch you action at the line I'm point at, it will go and exec your actions, and then you could receive the newly updated props in an event like componentWillReceiveProps
...
receiving new props
to your component will cause your component to re render
So, console logging your props immediately after executing your action, will never give you the new state
... wait for it in componentWillReceiveProps
or render
methods
here's an example of how to get your new props (todos) in your case:
componentWillReceiveProps(nextProps) {
const { todos } = nextProps;
console.log('I recieved new todos', todos);
}
also, if your render
method render any component that display this todos
field that you grap from this.props.todos
... also will be updated automatically...
Upvotes: 2