My app has a settings screen (child component) where you can change information about yourself and I'm trying to get that to render on my app's profile screen (parent component). So the profile screen displays your info and if you want to change any info you do it in settings. Right now any changes I make in the settings screen show up in Firebase but if I go back to the profile screen the changes in settings don't render. Of course if I close the app and reload it the changes will be there because the changes in settings are registering to firebase; however, the state is not passing up from the child component to the parent. Does anyone have any advice on how to pass state from the settings (child) component up to the profile (parent) component?
You can try redux, It store data in state by props whenever you change data in redux store.
Other idea is, pass a setState method to child component.
class Parent extends Component {
updateState (data) {
this.setState(data);
}
render() {
<View>
<Child updateParentState={this.updateState.bind(this)} />
</View>
}
}
class Child extends Component {
updateParentState(data) {
this.props.updateParentState(data);
}
render() {
<View>
<Button title="Change" onPress={() => {this.updateParentState({name: 'test'})}} />
</View>
}
}
You should look into a state management module such as Redux to see if it would work with your app, but without anything you can achieve it by doing something like this:
// ---------------------------------------------
// Parent:
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={val => this.updateData(val)} />
);
}
}
// ---------------------------------------------
// Child:
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick()}>Test</button>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With