Warning: Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Context.consumer`) - react-native

here my context file
import React from 'react';
import storage from '#helper/storage/user-storage';
export const AuthContext = React.createContext();
class AuthContextProvider extends React.Component{
state = {
user: null,
nigth_mode: false,
token: null
}
login = async ({user, token}) => {
await storage.storeUser(user)
await storage.storeToken(token)
this.setState({
user: user,
token: token
})
}
logout = async () => {
storage.removeAll().then(() => {
this.setState({
user: null,
token: null
})
});
}
setUser = async (data) => {
this.setState({
user: data
})
}
nigth_mode = async () => {
this.setState({
nigth_mode: !nigth_mode
})
}
render(){
return(
<AuthContext.Provider
value={{
...this.state,
login: this.login,
logout: this.logout,
setUser: this.setUser,
nigth_mode: this.nigth_mode,
token: this.state.token
}}
>
{ this.props.children }
</AuthContext.Provider>
);
}
}
export default AuthContextProvider
in my login file i have this render
render(){
return(
<AuthContext.Consumer>
{context => {
console.log('token', context)
if(context.token){
// this.props.navigation.reset({
// index: 0,
// routes: [{ name: 'Home' }],
// });
this.props.navigation.navigate('View')
}else{
return(
<LinearGradient
colors={['#232526', '#182848']}
style={styles.mainContainerLogin}>
<KeyboardAvoidingView
style={styles.mainContainerLogin}
behavior={'height'}
>
{/* <View style={styles.loginLogo}>
<Image
source={require('../Images/ic-logo.jpg')}
style={styles.logo}
/>
</View> */}
<View style={styles.inputContainer}>
<Ionicon
name="md-person"
size={20}
color="rgb(110,182,245)"
style={styles.inputIcon}
/>
<TextInput
placeholder={'Email'}
placeholderTextColor={'rgba(255,255,255,0.5)'}
underlineColorAndroid="transparent"
style={styles.loginInput}
onChangeText={value => (this.userref = value)}
/>
</View>
<View style={styles.inputContainer}>
<Ionicon
name="md-lock-closed"
size={20}
color="rgb(110,182,245)"
style={styles.inputIcon}
/>
<TextInput
placeholder="Password"
placeholderTextColor={'rgba(255,255,255,0.5)'}
underlineColorAndroid="transparent"
secureTextEntry={this.state.keyHide}
style={styles.loginInput}
onChangeText={value => (this.password = value)}
/>
<TouchableOpacity
style={styles.btnEye}
onPress={this._showPassword.bind(this)}>
<Ionicon
name={
this.state.press == false ? 'md-eye' : 'md-eye-off'
}
size={20}
color="rgb(110,182,245)"
/>
</TouchableOpacity>
</View>
{this._displayLoading()}
{_errorTextLogin(this.state.error)}
</KeyboardAvoidingView>
</LinearGradient>
);
}
}}
</AuthContext.Consumer>
);
so on clicking login button, the context.login is called, so it's set the state of token, so in my condition if my context.token exist i navigate to another page; if i console log on context.token, i got eh token when login is success,then the navigation is processed successfuly but i got a error popup on the new page
Warning: Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Context.consumer`)

Related

initialState resets after dispatch actions in react useReducer

In my app, I fetch users data from the server inside the useEffect hook and set the initialState of the useReducer. When action dispatch happens on text input change, the initialState resets instead of updating thus I can't type a word inside the input. Can someone figure out the problem, please? I'm fairly new to react reducers. I have attached the relevant codes. Thanks.
EditProfile.js
const EditProfile = ({ navigation, route }) => {
const userid = route.params.userid;
const { user } = React.useContext(AuthContext);
const [userData, setUserData] = React.useState(null);
const initialState = {
name: userData ? (userData.name ? userData.name : "") : "",
dob: userData ? (userData.dob ? userData.dob.toDate() : "") : "",
phone: userData ? (userData.phone ? userData.phone : "") : "",
location: userData ? (userData.location ? userData.location : "") : "",
caption: userData ? (userData.caption ? userData.caption : "") : "",
};
React.useEffect(() => {
async function fetchData() {
const response = await getUserData(userid);
setUserData(response);
}
fetchData();
}, []);
const reducer = (state, action) => {
switch (action.type) {
case "nameInputChange":
return {
...state,
name: action.name,
};
case "dobInputChange":
return {
...state,
dob: action.dob,
};
case "phoneInputChange":
return {
...state,
phone: action.phone,
};
case "locationInputChange":
return {
...state,
location: action.location,
};
case "captionInputChange":
return {
...state,
caption: action.caption,
};
}
};
const [data, dispatch] = React.useReducer(reducer, initialState);
const nameInputChange = (value) => {
dispatch({
type: "nameInputChange",
name: value,
});
console.log("Name: ", initialState.name);
};
const dobInputChange = (date) => {
dispatch({
type: "dobInputChange",
dob: date,
});
};
const phoneInputChange = (value) => {
dispatch({
type: "phoneInputChange",
phone: value,
});
};
const locationInputChange = (value) => {
dispatch({
type: "locationInputChange",
location: value,
});
};
const captionInputChange = (value) => {
dispatch({
type: "captionInputChange",
caption: value,
});
};
return (
<View>
<FlatList
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => (
<View>
<TouchableOpacity>
<Image
source={require("../assets/images/profile.jpg")}
style={{ width: "98%", height: "98%", borderRadius: 59 }}
/>
<View>
<Entypo name="camera" color="#8000e3" size={18} />
</View>
</TouchableOpacity>
<View>
<VerticalNameInput
type="name"
label="Full Name"
placeholder="Full name"
color="#9798ac"
placeholder="enter your full name"
onChangeText={(value) => nameInputChange(value)}
value={initialState.name}
/>
<VerticalDateInput
label="Date of Birth"
color="#9798ac"
dobInputChange={dobInputChange}
initialState={initialState}
/>
</View>
<View>
<VerticalNameInput
type="mobile"
label="Mobile"
color="#9798ac"
placeholder="mobile number"
onChangeText={(value) => phoneInputChange(value)}
value={initialState.phone}
/>
<VerticalNameInput
type="location"
label="Location"
color="#9798ac"
placeholder="city and country"
onChangeText={(value) => locationInputChange(value)}
value={initialState.location}
/>
</View>
<View>
<VerticalNameInput
type="caption"
label="Profile Caption"
color="#9798ac"
placeholder="enter about yourself"
onChangeText={(value) => captionInputChange(value)}
value={initialState.caption}
/>
</View>
</View>
)}
/>
<View style={{ position: "relative", top: -90, left: 200 }}>
<FloatingAction
onPressMain={() => {
updateUser(userid, userData);
}}
floatingIcon={<Entypo name="check" size={28} color="#fff" />}
/>
</View>
</View>
);
};
export default EditProfile;
VerticalNameInput.js
const VerticalNameInput = ({ label, color, placeholder, type, ...rest }) => {
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
{type === "name" ? (
<AntDesign name="user" color="#000" size={15} />
) : type === "mobile" ? (
<AntDesign name="mobile1" color="#000" size={15} />
) : type === "location" ? (
<EvilIcons name="location" color="#000" size={20} />
) : type === "caption" ? (
<Ionicons
name="information-circle-outline"
color="#000"
size={18}
/>
) : null}
</View>
<TextInput
style={{ width: "85%", height: "100%" }}
numberOfLines={1}
placeholder={placeholder}
placeholderTextColor={color}
{...rest}
/>
</View>
</View>
);
};
export default VerticalNameInput;
VerticalDateInput.js
const VerticalDateInput = ({ label, color, dobInputChange, initialState }) => {
const [date, setDate] = React.useState(new Date());
const [open, setOpen] = React.useState(false);
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
<AntDesign name="calendar" color="#000" size={15} />
</View>
<View>
<Text style={{ marginLeft: 10 }}>
{initialState.dob
? initialState.dob.toDateString()
: new Date().toDateString()}
</Text>
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => setOpen(true)}
>
<AntDesign name="caretdown" color="#000" size={12} />
</TouchableOpacity>
</View>
<DatePicker
maximumDate={new Date()}
mode="date"
modal
open={open}
date={initialState.dob ? initialState.dob : date}
onConfirm={(date) => {
setOpen(false);
setDate(date);
dobInputChange(date);
}}
onCancel={() => {
setOpen(false);
}}
/>
</View>
</View>
);
};
export default VerticalDateInput;
Try add "default" case return current state in your reducer.
It might happen that you dispatch some unknown action, and reducer return undefined as a result.
const reducer = (state = initialState, action) => {
switch (action.type) {
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state
}
}

React Native Context, how to share context beetwing multiple nested files and components

I'm quiete new to react native, and im stuck on passing context between components in different files
basically im building login flow following the react navigation auth-flow https://reactnavigation.org/docs/auth-flow/
my scenario looks as follow:
in App.js
a stack screen with Login/Register/Home, showing Login/Register or Home based on login status
the Home Screen is made by a component which is a drawer, using a custom drawer and two component (Home and About)
//VARIOUS IMPORT
const Drawer = createDrawerNavigator();
const HeaderOption = () => ({
headerShown: false,
// animationTypeForReplace: state.isSignout ? 'pop' : 'push',
});
const AppStack = createStackNavigator();
const AuthContext = createContext();
//THE DRAWER FOR HOME
function DrawerNavigator(props) {
return (
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => MyDrawer(props)}
>
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="About" component={About} />
</Drawer.Navigator>
);
}
//MAIN APP
export default function App({ navigation }) {
const [state, dispatch] = useReducer(
(prevState, action) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
userToken: action.token,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
userToken: null,
};
}
},
{
isLoading: true,
isSignout: false,
userToken: null,
}
);
useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let userToken;
try {
userToken = await AsyncStorage.getItem('userToken');
} catch (e) {
}
dispatch({ type: 'RESTORE_TOKEN', token: userToken });
};
bootstrapAsync();
}, []);
const authContext = useMemo(
() => ({
signIn: async (data) => {
// LOGIN PROCEDURE
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
signOut: () => dispatch({ type: 'SIGN_OUT' }),
signUp: async (data) => {
// SUBSCRIBE PROCEDURE
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
}),
[]
);
if (state.isLoading) {
// We haven't finished checking for the token yet
return (
<View>
<Text>Loading</Text>
</View>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<AppStack.Navigator initialRouteName="Login">
{state.userToken == null ? (
<>
<AppStack.Screen
name="Login"
component={LoginScreen}
options={HeaderOption}
/>
<AppStack.Screen
name="Register"
component={RegisterScreen}
options={HeaderOption}
/>
</>
) : (
<AppStack.Screen
name="HomeApp"
component={DrawerNavigator}
options={HeaderOption}
/>
)}
</AppStack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
}
in LoginScreen.js
the effective login screen (which is showed at app startup if not logged in)
//import
export default function LoginScreen(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const { signIn } = useContext(AuthContext);
return (
<View
style={{
flex: 1,
backgroundColor: Constants.MAIN_GREEN,
}}
>
<View style={{ ...styles.container }}>
<StatusBar hidden={true} />
<View style={{ ...styles.logoContainer }}>
<Image
style={styles.logoIcon}
source={require('../assets/logo_popeating_amp.png')}
/>
</View>
<View style={{ ...styles.inputContainer }}>
<Image
style={styles.inputIcon}
source={require('../assets/mail.png')}
/>
<TextInput
autoFocus={true}
placeholder="Email address"
onChangeText={(email) => setEmail(email)}
value={email}
label="Email"
style={styles.inputs}
keyboardType={'email-address'}
/>
</View>
<View style={{ ...styles.inputContainer }}>
<Image
style={styles.inputIcon}
source={require('../assets/password.png')}
/>
<TextInput
placeholder="Password"
onChangeText={(password) => setPassword(password)}
value={password}
secureTextEntry={true}
label="Password"
style={styles.inputs}
/>
</View>
<TouchableHighlight
style={[styles.buttonContainer, styles.loginButton]}
onPress={() => signIn({ email, password })}
underlayColor={Constants.HI_COLOR}
>
<Text style={styles.loginText}>LOGIN</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => props.navigation.navigate('HomeApp')}
underlayColor={Constants.HI_COLOR}
>
<Text>Forgot your password?</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonContainer}
onPress={() => props.navigation.navigate('Register')}
underlayColor={Constants.HI_COLOR}
>
<Text>Register</Text>
</TouchableHighlight>
</View>
</View>
);
}
const styles = StyleSheet.create({
//styles
});
in DrawerContent.js
the drawer for the home which contain a link to Home, a link to About, a link to Logout
in Home.js
the main page which is the initialroute of the Drawer
every time i try to start the app
the error is
Unhandled promise rejection: ReferenceError: Can't find variable: AuthContext
it seems LoginScreen cant access AuthContext, how can i have AuthContext available to other components between files?
You can place the context creation in a separate file
//AuthContext.js
const AuthContext = createContext();
export default AuthContext;
In app.js you can simply import this and use this
import AuthContext from './AuthContext.js';
You can do the same for login.js as well
Then it will work as expected.

Navigating to another screen after user authentication

I have a login app some users in a Firebase database. When a user logs in into their account succesfully, I want to redirect them to another screen I have. Unfortunately, every single approach I've tried since a couple of days does not work as intended.
This is my code, I'm omitting the StyleSheet and the libraries (and yes, I have my other screen imported into the App.js)
class HomeScreen extends Component {
state = { username: null, password: null, nonValidInput: null }
_onSubmit = ({ navigation }) =>{
const { navigate } = this.props.navigation;
if(EmailValidator.validate(this.state.username) == true) {
this.setState({ nonValidInput: false });
const { username, password } = this.state;
try {
firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(navigator.navigate('Age'));
} catch {
Alert.alert(
'Error',
'Los datos no son correctos',
[
{ text: 'Ok' }
],
{ cancelable: false }
);
}
} else {
this.setState({ nonValidInput: true });
}
}
render() {
return (
<KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
<View style={styles.logo}>
<Image source = {logo} style={styles.img}/>
<Text style={styles.textLogoPrimary}>Neuron App</Text>
<Text style={styles.textLogoSecondary}>Test</Text>
</View>
<View style={styles.formElement}>
<Text style={styles.formText}>Correo Electrónico</Text>
<TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
style={styles.formInput} />
{this.state.nonValidInput ? (
<Text style={styles.textAlert}>Correo electrónico no valido.</Text>
) : null}
</View>
<View style={styles.formElement}>
<Text style={styles.formText}>Contraseña</Text>
<TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
secureTextEntry={true}/>
</View>
<View style={styles.buttonView}>
<TouchableOpacity style={styles.button} onPress={this._onSubmit}>
<Text style={styles.buttonText}>Iniciar</Text>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
);
}
}
const Stack = createStackNavigator();
class App extends Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='Age' component={AgeInput} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
Thanks for your help
What is navigator? You can use navigate from navigation prop directly:
firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
Also, make sure you call the function in the then clause in the right way.

Cannot get value from TextInput

I'm currently encounter a particular issue with my Edit page code. The problem is as follow: when the user wants to edit their username (on the application), if the user types the (new) username in the textInput field (called 'name')and clicks on the button (Image button of a pencil) , the application is not changing the username. During debugging, the debugger tells me that name is undefined. below follows the code snippet:
edit(name) {
let { user } = this.state;
if (user) {
user.updateProfile({
displayName: name, // here i get the error of 'Undefied'
}).then(() => {
// Update successful.0
}).catch((error) => {
// An error happened.
});
}
}
Below follows the full code of the page:
//constructor
constructor() {
super();
this.state = {
user: {},
fetching: true,
}
this.onAuthStateChanged = this.onAuthStateChanged.bind(this);
}
componentDidMount() {
//Functionality
this.unsubscribeOnAuthChange = firebase.auth().onAuthStateChanged(this.onAuthStateChanged);
}
componentWillUnmount() {
this.unsubscribeOnAuthChange();
}
onAuthStateChanged(user) {
this.setState({ user, fetching: false })
}
edit(name) {
let { user } = this.state;
if (user) {
user.updateProfile({
displayName: name,
}).then(() => {
// Update successful.0
}).catch((error) => {
// An error happened.
});
}
}
ok = () => {
this.props.navigation.navigate('Home');
}
//Styles Account
render() {
let { user, fetching } = this.state;
if(fetching) return null;
return (
<ScrollView>
<View style={styles.container}>
<Text style={styles.text}>Account</Text>
<View style={styles.row}>
<Image source={require('./Picture/userImage1.png')} />
<TouchableOpacity onPress={() => this.edit(user.name)}>
<Image source={require('./Picture/pencil.png')} style={styles.pencil} />
</TouchableOpacity>
</View>
<Text style={styles.text1}>Welcome {user.displayName}</Text>
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(name) => this.setState({name})}
underlineColorAndroid='transparent'
autoCapitalize='none'
/>
<TouchableOpacity
style={styles.btn}
onPress={() => this.ok()}>
<Text style={{ fontSize: 17, color: '#fff' }}>Ok</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
Can anyone give me some advice of why i'm getting an 'undefined" error when the user clicks on the image button?
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(name) => this.setState({name})} //<---Here you set value in state call `name`
underlineColorAndroid='transparent'
autoCapitalize='none'
/>
While HERE you are passing the value of object key name
<TouchableOpacity onPress={() => this.edit(user.name)}>
Just simply define name state in this.state and pass the value of state this.state.name in edit function.

react-native redux can't access and update data

App.js
import React, { Component } from 'react';
import UserApp from './MainApplication';
import store from './store/index';
import { Provider } from 'react-redux';
class App extends Component {
render() {
return (
<Provider store={store}>
<UserApp />
</Provider>
);
}
}
reducer:
import { ADD_USER } from '../actions/actionTypes';
// import { initialState } from '../store/initialState';
const initialState = {
id: 0,
username: 'test',
// email: '',
// password: '',
// otp: false,
// otpColor: 'red',
// otpStatus: 'Send OTP',
};
const addUser = (state = initialState, action) => {
switch (action.type) {
case ADD_USER:
return Object.assign({}, state, {
//id: action.payload.id,
username: action.data,
// email: action.email,
// password: action.password,
// otp: action.otp,
// otpColor: action.otpColor,
// otpStatus: action.otpStatus,
});
}
return state;
};
export default addUser;
export default App;
actionCreator:
import { ADD_USER, ADD_IMAGE, UPDATE_API, SEND_OTP } from './actionTypes';
let nextID = 0;
export const addUser = (data) => ({
type: ADD_USER,
id: (nextID += 1),
data,
});
component:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
Button,
TextInput,
} from 'react-native';
import { ImagePicker, Permissions } from 'expo';
// import Icon from 'react-native-vector-icons/Ionicons';
import { connect } from 'react-redux';
class Users extends Component<Props> {
constructor(props) {
super(props);
this.state = {
image: null,
};
}
_pickImage = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === 'granted') {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri });
}
} else {
throw new Error('Camera roll permission not granted');
}
};
render() {
//const { fullName, email, password } = this.props.navigation.state.params;
let { image } = this.state;
return (
<View style={styles.mainContainer}>
<View styles={styles.container}>
<TouchableOpacity style={styles.imageContainer}>
image &&
<Image source={{ uri: image }} style={styles.image} />
</TouchableOpacity>
<Button
title={
this.state.image === null
? 'Pick an image from camera roll'
: 'Change Image'
}
onPress={this._pickImage}
/>
<View>
<Text style={styles.label}>Full Name: </Text>{' '}
<TextInput
placeholder={this.props.username}
//onChangeText={email => this.setState({ email })}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={styles.label}>Email: </Text>
<TextInput
placeholder={this.props.email}
//onChangeText={email => this.setState({ email })}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Home')}
style={styles.btnContainer}>
<Text style={styles.btn}>FINISH</Text>
</TouchableOpacity>
</View>
<View>
<Text>username: {this.props.username}</Text>
</View>
</View>
);
}
}
const mapStateToProps = state => ({
username: state.username
});
export default connect(mapStateToProps)(Users);
desired Component:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
TextInput,
KeyboardAvoidingView,
TouchableOpacity,
ScrollView,
} from 'react-native';
import { connect } from 'react-redux';
// import { addUser } from '../reducers/addUser';
import { addUser } from '../actions';
import { ADD_USER } from '../actions/actionTypes';
class SignUp extends Component<Props> {
constructor(props) {
super(props);
// local state..
this.state = {
username: '',
email: '',
password: '',
otp: false,
otpColor: 'red',
otpStatus: 'Send OTP',
};
}
// addUser = (username) => {
// this.props.dispatch({ type: ADD_USER, username })
// }
render() {
//const { navigate } = this.props.navigation;
//const newUser = this.state;
return (
<View style={styles.mainContainer}>
<View style={styles.header}>
<View style={styles.createAccountContainer}>
<Text style={styles.createAccount}> Create an account </Text>
<View style={styles.underLineRight} />
</View>
<View style={styles.singInContainer}>
{' '}
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Login')}>
<Text style={styles.signupHeader}> Sign In </Text>
</TouchableOpacity>
<View style={styles.underLineLeft} />
</View>
</View>
<View style={styles.content}>
<TextInput
placeholder="FULL NAME"
value={this.state.username}
onChangeText={username => this.setState({ username })}
// onSubmitEditing={() => this.newUser.email.focus()}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<View style={styles.emailContainer}>
<TextInput
placeholder="EMAIL"
value={this.state.email}
onChangeText={email => this.setState({ email })}
//onSubmitEditing={() => this.newUser.password.focus()}
keyboardType="email-address"
style={[styles.input, { flex: 2 }]}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<TouchableOpacity
value={this.state.email}
onPress={() => {
this.setState({
otp: true,
otpStatus: 'OTP Send',
otpColor: 'green',
});
}}
style={styles.otpInput}>
<Text style={{ color: this.state.otpColor }}>
{this.props.otpStatus}
</Text>
</TouchableOpacity>
</View>
<TextInput
placeholder="PASSWORD"
value={this.state.password}
//onChangeText={password => this.setState({ password })}
style={styles.input}
secureTextEntry={true}
returnKeyType="go"
/>
<TouchableOpacity
onPress={() => {
console.log(
this.props.username + 'removeID TouchableOpacity(104)-- Users.js'
);
if (this.props.addNewUser()) this.props.navigation.navigate('Users');
}}
// onPress={() =>
// navigate('Users', {
// username: username,
// email: email,
// password: password,
// })
// }
style={styles.btnContainer}>
<Text style={styles.btn}>Sign up</Text>
</TouchableOpacity>
</View>
<View style={styles.orContainer}>
<Text style={{ color: 'grey' }}>─────</Text>
<Text style={styles.or}>Or</Text>
<Text style={{ color: 'grey' }}>─────</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity style={styles.labelsGoogle}>
<Text style={styles.btn}>google</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.labelfacebook}>
<Text style={styles.btn}>facebook</Text>
</TouchableOpacity>
</View>
<View>
<Text>username: {this.props.username}</Text>
</View>
</View>
);
}
}
// Add to the props of this class..
const mapStateToProps = state => {
console.log(state);
return {
username: state.username,
// email: state.email,
// otp: state.otp,
// otpColor: state.otpColor,
// otpStatus: state.otpStatus,
};
};
// Add to the props of this class..
const mapDispatchToProps = (dispatch) => ({
addNewUser: username => dispatch(addUser(username)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(SignUp);
problems are,
cannot map my initial state to the component.
not able to update the state.
i don't have a senior to ask and i'm a beginner. done a lot of surfing. the proj was working properly till converted to redux. require help. thanks in advance..
First of all, You can call action method in componenet and
import { addUser } from '../actions'; // import
this.props.addUser(); // call method
export default connect(mapStateToProps, { addUser })(Users); // connect actions method
Than you can set the reducers file in bellow
export default (state = initialState, action) => {
switch (action.type) {
case ADD_USER:
return Object.assign({}, state, {
//id: action.payload.id,
username: action.data,
// email: action.email,
// password: action.password,
// otp: action.otp,
// otpColor: action.otpColor,
// otpStatus: action.otpStatus,
});
default:
return state;
}
};