How can I call setState from a different class that is in the same file but different class? - react-native

I call a function that is in my Homepage class from my ProfileScreen class that is in the same .js file. I successfully did that, but in that function a setState is called, and when the function is called from the other class, the state doesn't change. How can I get this.state.user in HomePage to change from calling the onPressLogout function in the ProfileScreen class?
export default class HomePage extends Component<Props> {
state = {
email:'',
password:'',
firstname:'',
lastname:'',
user:true,
error: '',
}
onPressLogout(){
firebase = require('firebase');
firebase.auth().signOut()
.then(() => this.setState({
user:false
}))
.catch(() => this.setState({
error: 'Logout Failure',
}))
}
render(){
return <AppContainer>
</AppContainer>;
}
}
class ProfileScreen extends React.Component {
constructor(props) {
super(props);
Obj = new HomePage();
}
render() {
return (
...
<TouchableOpacity style={styles.button} onPress =
{()=>Obj.onPressLogout()}>
</TouchableOpacity>
...
}
}
const TabNavigator = createBottomTabNavigator({
Profile: ProfileScreen,
});
const AppContainer = createAppContainer(TabNavigator);
I get this warning when I run the code and the this.state.user doesn't change:
Warning: Can't call "setState" on a component that is not yet mentioned.

You should pass the function of the parent element into the child element as a prop. Then, you can call it in the child to manipulate the state of the parent class.
Here is an example,
class ChangeButton extends React.Component{
render(){
return (
<Button title="Change" onPress={this.props.updateMainState}/>
)
}
}
export default class App extends React.Component {
state = {
name: 'Fatih'
}
changeName = ()=> {
this.setState({
name: 'Faruk'
})
}
render() {
return (
<View style={styles.container}>
<Text>
{this.state.name}
</Text>
<ChangeButton updateMainState={this.changeName}/>
</View>
);
}
}
In the code above, we passed changeName function into the ChangeButton element. The Button in ChangeButton calls the function of the parent element when you press it, which manipulates the state of the main class.
Here is the working code: ProjectLink

Related

React navigation- import file navigate page

This file import
class Footer extends Component {
_notifications = () => {
const { navigate } = this.props.navigation;
navigate('Ntf', {});
}
render() {
return (<TouchableHighlight onPress={() => this._notifications()} ></TouchableHighlight>);
}
}
This file main ( React-Navigation - NavigationDrawerStructure ).
import { Footer } from './Footer';
export default class HomePage extends Component {
render() {
return (<View><Footer/></View>);
}
Click _notifications button after error : undefined is an object c.props.navigation.navigate
Help me please
Only the components defined in routes has access to the navigation props not the child of those components!.
Solution:-
import file
class Footer extends Component {
_notifications = () => {
this.props.NavigateToNTF()
}
render() {
return (<TouchableHighlight onPress={() => this._notifications()} ></TouchableHighlight>);
}
}
main file:-
import { Footer } from './Footer';
export default class HomePage extends Component {
render() {
return (<View><Footer NavigateToNTF={()=> this.props.navigation.navigate('Ntf', {}) } /></View>);
}
Navigation props are not available in child component that's why you are getting undefined when you call navigation props but with this solution we are sending props from the parent file (main file) to the child (export file) so that way it will work!.
If it helps! make sure to motivate me 😜 you know what i mean!.

I am trying to open modal from the child component

I have tried many ways but non of these worked. I am trying from 5 days.
I used redux,props,then ref . Non of these helped.
I need the modal to be visible when I call it from another class.
// this is the parent class
export default class Search1 extends React.Component {
constructor(props) {
super(props);
this.setModalVisible1 = this.setModalVisible1.bind(this);
this.state = {
modalVisible1: false,
};
this.closeModal = this.closeModal.bind(this);
}
setModalVisible1(visible) {
this.setState({ modalVisible1: visible });
// this.setModalVisible2(visible);
}
closeModal() {
console.log("modalvi1 value is in closemodal ", this.state.modalVisible1);
this.setState({ modalVisible1: false });
}
render() {
return (
{/* it renders the screen again when I call the */}
<Modal
closeModal={() => this.closeModal}
animationType="slide"
transparent={true}
visible={this.state.modalVisible1}
</Modal>
<NavStack />
);
}
}
// this is the child class
class HomeScreen extends React.Component {
render() {
<TouchableOpacity
style={styles.firstStyle}
onPress={() => {
this.props.closeModal();
);
}}
>
return (
}
The modal should be visible when called from outer child class. It needs to be close when called from the parent class.
I tried using redux. that does not worked. Then I used props. Then I used the ref. None of these helped. Just get tired of this. Help me out of this.
Pass the function to modal
closeModal() {
this.setState({ modalVisible1: false });;
}
<Modal
closeModal={this.closeModal}
animationType="slide"
transparent={true}
visible={this.state.modalVisible1} />
and run it on child component as this.props.closeModal()

How do I update Different Screens form another independent screen?

I have an App with a navigationbar with 2 Screens.
When i apply a function on Screen/Component 1 , I want to render or trigger a change in the Second Screen.
is there a way to either re-render the screen on Enter or to update the state of the other screen ?
Component one:
export default class HomeScreen extends React.Component {
constructor() {
super();
}
_onPress(){
try {
await AsyncStorage.setItem('value', 'changed Value');
} catch (error) {
console.log(error.message);
}
console.log("saved: " + this.state.userName )
}
render() {
return (
<View style={styles.container}>
<Button title="btn" onPress={() => this._onPress()} >
</Button>
</View>
)
}
component 2:
export default class SecondScreen extends React.Component {
constructor() {
super();
this.state = {some : ''}
}
async getValue () {
let recievedValue = '';
try {
let promise = await AsyncStorage.getItem('value') || 'cheeseCake';
promise.then((value) => recievedValue = value)
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return recievedValue
}
render() {
var value= this.getValue();
return (
<View style={styles.container}>
<Text>
HERE CHANGED VALUE: {value}
</Text>
<Button onPress={()=> this.setState((prev)=> {some:'Thing'})}>
</Button>
</View>
)
}
When i press the Button on screen 1(HomeScreen) the value is saved.
But it only shows in the secont screen when I trigger a statechange via Button Press.
How do I render the screen when I visit the screen via navigation bar ?
Did you try EventEmiter?
Use this custom event listener: https://github.com/meinto/react-native-event-listeners
eg:
import { EventRegister } from 'react-native-event-listeners'
/*
* RECEIVER COMPONENT
*/
class Receiver extends PureComponent {
constructor(props) {
super(props)
this.state = {
data: 'no data',
}
}
componentWillMount() {
this.listener = EventRegister.addEventListener('myCustomEvent', (data) => {
this.setState({
data,
})
})
}
componentWillUnmount() {
EventRegister.removeEventListener(this.listener)
}
render() {
return <Text>{this.state.data}</Text>
}
}
/*
* SENDER COMPONENT
*/
const Sender = (props) => (
<TouchableHighlight
onPress={() => {
EventRegister.emit('myCustomEvent', 'it works!!!')
})
><Text>Send Event</Text></TouchableHighlight>
)

Passing Navigator object in renderItem

I'm struggling to make Navigator object visible in List Component.
Here the code explained: as you can see in RootDrawer, I have Concept component. It simply shows a list of items based on a id passed in param.
Each item points to another Concept with another id, but I get
undefined is not an object (evaluating 'navigation.navigate')
when I press on that <RippleButton> with onPress={() => navigation.navigate('Concept',{id:12}). The problem here I'm not passing the Navigation object correctly. How can I solve?
main Navigator drawer
const RootDrawer = DrawerNavigator(
{
Home: {
screen: StackNavigator({
Home: { screen: Home }
})
},
Search: {
screen: StackNavigator({
Cerca: { screen: Search },
Concept: { screen: Concept },
})
}
}
);
Concept component
export default class Concept extends Component {
loading = true
static navigationOptions = ({ navigation,state }) => ({
headerTitle: "",
title: `${navigation.state.params.title}` || "",
})
constructor(props) {
super(props);
}
async componentDidMount(){
}
render() {
const { params } = this.props.navigation.state;
const id = params ? params.id : null;
const { t, i18n, navigation } = this.props;
const Concept = DB.get(id)
return (
<View>
<ScrollView>
<List data={Concept.array|| []} title={"MyTile"} navigation={navigation} />
</ScrollView>
</View>
);
}
}
List Component
class List extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { navigation } = this.props;
}
_renderItem = (item,navigation) => (
<RippleButton
id={item.id}
onPress={() => navigation.navigate('Concept', { id: 12, otherParam: 'anything you want here'})}> //this line throws the error
<Text>{item.Term}</Text>
</RippleButton>
)
render() {
const { navigation } = this.props;
return (
<View>
<FlatList
data={this.props.data}
renderItem={({item}) => this._renderItem(item, navigation)}
/>
</View>)
}
}
Instead of passing the navigation prop, you can try using the withNavigation HOC.
Where your List Component is defined:
import { withNavigation } from 'react-navigation`
....
export default withNavigation(List)
Now the List component will have access to the navigation prop

Update state when user press back button in React Native

I use react-navigation for manage routes. This is my Home component:
class HomeScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: {
firstname: 'John',
avatar: 'john-profile.png',
location: 'Canada',
}
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
render() {
return (
<View>
<Image src="{this.state.userProfile.avatar}" />
<Text>Firstname: {this.state.userProfile.firstname}</Text>
<Text>Location: {this.state.userProfile.location}</Text>
</View>
);
}
}
And this is the Profile screen:
class ProfileScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: null,
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
save() {
var userSavedProfile = this.state.userProfile;
userSavedProfile.firstname = "Peter";
userSavedProfile.avatar = "peter-avatar.png";
userSavedProfile.location = "EEUU";
this.setState({userProfile: userSavedProfile});
AsyncStorage.setItem('userProfile', JSON.stringify(this.state.userProfile), () => {});
}
render() {
return (
<View>
<Button title="Save" onPress={() => this.save()} />
</View>
);
}
}
When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?
You can use BackHandler from react-native
https://facebook.github.io/react-native/docs/backhandler.html
You can change state inside function of backhandler
I think that your application would need a state manager, where you could store your user information and access it anywhere in the app. You should take a look at Redux. It would fit your needs and the info in your Home screen would automatically update.
but for anyone who will need this functionality in there react native application here is the solution you can try.
using react navigation.
import {withNavigationFocus} from "react-navigation";
class Profile extends Component {
...
}
export default withNavigationFocus(Profile);
There can be two workarounds check it out -
1 Send callback in params
class HomeScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: {
firstname: 'John',
avatar: 'john-profile.png',
location: 'Canada',
}
}
this.getUserData = this.getUserData.bind(this);
}
componentDidMount() {
this.getUserData;
}
getUserData = () =>{
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
render() {
return (
<View>
<Image src="{this.state.userProfile.avatar}" />
<Text onPress={()=>this.props.navigation.navigate('ProfileScreen', this.getUserData)}>Firstname: {this.state.userProfile.firstname}</Text>
<Text>Location: {this.state.userProfile.location}</Text>
</View>
);
}
}
class ProfileScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: null,
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
save() {
var userSavedProfile = this.state.userProfile;
userSavedProfile.firstname = "Peter";
userSavedProfile.avatar = "peter-avatar.png";
userSavedProfile.location = "EEUU";
this.setState({userProfile: userSavedProfile});
AsyncStorage.setItem('userProfile', JSON.stringify(this.state.userProfile), () => {});
//this is the magic
this.props.navigation.state.params.getUserData();
}
render() {
return (
<View>
<Button title="Save" onPress={() => this.save()} />
</View>
);
}
}
2 On HomeScreen Constructor add this (Dirty one)
this.props.navigation.addListener(
'didFocus',
payload => {
this.setState({is_updated:true});
}
);
You can use componentDidUpdate(){...} insted componentDidMount(){}