Reputation: 1890
I'm using react-native with react-redux and redux-thunk. Basically I have a Component
connected to store
which modifies some information from it with dispatch
. Despite every operation seems to be synchronous, I get old data on the next line after modification.
//reducer
import {assign as _assign} from 'lodash-es';
let initialState = {name: '1'};
export default (state = initialState, action) => {
switch (action.type) {
case 'Project renamed':
return _assign({}, state, {name: action.data});
default:
return state;
}
};
//Component
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Prompt from 'react-native-prompt';
class HomeScreen extends Component {
render() {
return <Prompt
onSubmit={() => {
this.props.onProjectRenamed('2');
console.log(this.props.currentProject.name) //Still get '1' here!!!
}}
/>;
}
}
const mapStateToProps = state => ({
currentProject: state.currentProject
});
const mapDispatchToProps = dispatch => ({
onProjectRenamed: (data) => dispatch({
type: 'Project renamed',
data: data
})
});
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
How can I get new this.props.currentProject.name
value?
Upvotes: 1
Views: 2701
Reputation: 32402
You can return a promise from your action and
const mapDispatchToProps = dispatch => ({
onProjectRenamed: (data) => {
dispatch({
type: 'Project renamed',
data: data
})
return Promise.resolve()
}
});
Now you can use then
on onProjectRenamed
onSubmit={() => {
this.props.onProjectRenamed('2').then(() => console.log(this.props.currentProject.name))
}}
Upvotes: 3
Reputation: 613
You are triggering an action when onSubmit
is invoked. This action is updating state object, which means your component will receive new props.
If you implement, ComponentWillReceiveProps
or ComponentWillUpdate
methods of your component, and then try to print, console.log(nextprops.currentProject.name)
inside it, you will get response as 2. simply try,
componentWillReceiveProps(nextProps) {
console.log(nexProps.currentProject.name)
}
Remember when render
method of your component is called after state has been updated, this.props.currentProject.name
will have the latest value i.e. 2.
Refer to React Component lifeCycle methods for more detail.
Upvotes: 1