Navigate callback react native

Viewed 10333

I have two screens. Home and PhotoDetails. On the Home I have photo list. I want to update the likes on the Home screen if I was like photo on the PhotoDetails screen. Without updating the entire page. Can I use a callback between screens? how? I'm using StackNavigator. thanks for the answer

 <TouchableHighlight
                                    onPress={() => navigate('PhotoDetails', {
                                        id: rowData.caption.id,
                                        tag: rowData.caption.text,
                                        url: rowData.images.standard_resolution.url,
                                        likes: this.state.likes[rowData.caption.id] || 0
                                    })}>
                                    <Image
                                        source={{uri:rowData.images.standard_resolution.url}}
                                        style={{width: 320, height: 320}}/>
                                </TouchableHighlight>

 <Like
                    onPress={()=> {onLike(this.state.id).then((newLikes)=>{
                        this.setState({
                            likes: newLikes
                        })
                    })}}
                    likes={this.state.likes + '' || '0'}
                />

1 Answers

In your case you should pass a callback function from home screen to child screen, wich will update the value. For example:

class HomeScreen extends Component {
    state = { likes: 0 }

    callback(likes) {
        this.setState({ likes: likes })
    }

    render() {
        const navigation = this.props.navigation;
        return (
            <View>
                <Text onPress={navigation.navigate('SomeChildScreen', { callback: this.callback.bind(this), likes: this.state.likes })}>Go to Child Screen</Text>
            </View>
        )
    }
}


class SomeChildScreen extends Component {

    liked() {
        const navigation = this.props.navigation;
        let likes = navigation.getParam('likes');
        likes++;
        navigation.getParam('callback')(likes);
        navigation.navigate('HomeScreen');
    }

    render() {
        const navigation = this.props.navigation;
        return (
            <View>
                <Text onPress={this.liked}>Like</Text>
            </View>
        )
    }
}

And pay atention how we must pass the callback function: this.callback.bind(this)

Related