Reputation: 329
I am developing a simple counter to learn react-redux
in React Native.
export default class Counter extends Component {
state = {
count: 0
}
reducer = (state = this.state, action) => {
// code
}
store = createStore(this.reducer);
render() {
return (
<View style={[Styles.container, { justifyContent: 'center' }]}>
<Provider store={this.store}>
<Controller />
</Provider>
</View>
);
}
}
The Controller
has 2 buttons to change the count
in parent component, and shows the value of count
as well. This is working fine. I can increase or decrease the value from the child component (Controller
) and the value of the child component also changes.
BUT,
Assume I add the below code in the parent component (Counter
).
state = {
count: 0
}
componentDidMount () {
setTimeout(() => this.setState({ count: 10 }), 5000);
}
In this case, once the state value changes in the parent component (Counter
) after 5 seconds, it doesn't update the value to 10 in child component (Controller
). It still shows 0. Is there anyway I can update the value in child component from the parent component?
Upvotes: 0
Views: 936
Reputation: 329
I just made a solution by myself by making a global function that returns createStore
.
redux/store.js
import { createStore } from 'redux';
export default function getStore(reducer) {
return createStore(reducer);
}
Counter.js
import store from './redux/store'
export default class Counter extends Component {
state = {
count: 0
}
reducer = (state = this.state, action) => {
switch (action.type) {
case actionTypes.INCREASE:
return { count: ++state.count };
case actionTypes.DECREASE:
return { count: --state.count };
default:
return state;
}
}
componentDidMount() {
setTimeout(() => this.setState({ count: 100 }), 2000);
}
render() {
return (
<View style={[Styles.container, { justifyContent: 'center' }]}>
<Provider store={store(this.reducer)}>
<Controller />
</Provider>
</View>
);
}
}
And this is exactly what I wanted. Now I can update the value from the child component and from the parent component as well. The value in the child component changes perfectly both the ways. But if anyone has another solution, you are welcome to post it here.
Upvotes: 0