Issue in transferring API data from one screen to another

46 Views Asked by At

This is the Screen 1(LoginScreen.js) code where we fetch the Data from an API, which responses in JSON format, where we will get 'custRegId', 'email', 'firstName', 'lastName' & 'mobileNumber'.

import {
  StyleSheet, TextInput, View, Text, ScrollView, Image, Keyboard, Button,
  TouchableOpacity, KeyboardAvoidingView, ActivityIndicator} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Loader from './Components/loader';
import axios from 'axios';
import HomeScreen from './drawerScreens/HomeScreen';

const LoginScreen = props => {
  let [userEmail, setUserEmail] = useState('');
  let [userPassword, setUserPassword] = useState('');
  let [loading, setLoading] = useState(false);
  let [errortext, setErrortext] = useState('');
  let [name, setName1] = useState('');
  let [item, setItem] = useState('');
  let [custRegId, setCustRegId] = useState('');

  const handleSubmitPress = () => {
    global.myUrl = 'Default API URL';
    setErrortext('');
    if (!userEmail) {
      alert('Please fill Email');
      return;
    }
    if (!userPassword) {
      alert('Please fill Password');
      return;
    }
    setLoading(true);
    var dataToSend = { email: userEmail, password: userPassword };
    var formBody = [];
    for (var key in dataToSend) {
      var encodedKey = encodeURIComponent(key);
      var encodedValue = encodeURIComponent(dataToSend[key]);
      formBody.push(encodedKey + '=' + encodedValue);
    }
    formBody = formBody.join('&');
    let data = {
      email: userEmail,
      password: userPassword
    }
    console.log(data.firstName)

    axios.post(myUrl, data, { withCredentials: true })
  .then(response => {console.log(response.data, "Logged in Successfully")
  .then((json) => {props.navigation.navigate('HomeScreen')})

      .catch(error => {
        setLoading(false);
        console.error("Incorrect Credentials");
      });
      console.log(setName1);
  });

  return (
    <View style={styles.mainBody}>
      <Loader loading={loading} />
      <ScrollView keyboardShouldPersistTaps="handled">
        <View style={{ marginTop: 100 }}>
          <KeyboardAvoidingView enabled>
            <View style={{ alignItems: 'center' }}>
              <Image
                source={require('../Image/aboutreact.png')}
                style={{
                  width: '90%',
                  height: 80,
                  resizeMode: 'contain',
                  margin: 30,
                }}
              />
            </View>
            <View style={styles.SectionStyle}>
              <TextInput
                style={styles.inputStyle}
                onChangeText={UserEmail => setUserEmail(UserEmail)}
                placeholder="Enter Email" 
                placeholderTextColor="#FFFFFF"
                autoCapitalize="none"
                keyboardType="email-address"
                ref={ref => {
                  this._emailinput = ref;
                }}
                returnKeyType="next"
                onSubmitEditing={() =>
                  this._passwordinput && this._passwordinput.focus()
                }
                blurOnSubmit={false}
              />
            </View>
            <View style={styles.SectionStyle}>
              <TextInput
                style={styles.inputStyle}
                onChangeText={UserPassword => setUserPassword(UserPassword)}
                placeholder="Enter Password" 
                placeholderTextColor="#FFFFFF"
                keyboardType="default"
                ref={ref => {
                  this._passwordinput = ref;
                }}
                onSubmitEditing={Keyboard.dismiss}
                blurOnSubmit={false}
                secureTextEntry={true}
              />
            </View>
            {errortext != '' ? (
              <Text style={styles.errorTextStyle}> {errortext} </Text>
            ) : null}
            <TouchableOpacity
              style={styles.buttonStyle}
              activeOpacity={0.5}>
              <Text style={styles.buttonTextStyle} 
              onPress={handleSubmitPress}>LOGIN</Text>
            </TouchableOpacity>
            <Text style={styles.registerTextStyle}>Don't have an account yet?</Text>
            <Text
              style={styles.registerTextStyle1}
              onPress={() => props.navigation.navigate('RegisterScreen')}>
               Register Here
            </Text>
          </KeyboardAvoidingView>
        </View>
      </ScrollView>
    </View>
  );
};
export default LoginScreen;

const styles = StyleSheet.create({
  mainBody: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#455a64',
  },
  SectionStyle: {
    flexDirection: 'row',
    height: 40,
    marginTop: 20,
    marginLeft: 35,
    marginRight: 35,
    margin: 10,
  },
  buttonStyle: {
    backgroundColor: '#5D6D7E',
    borderWidth: 0,
    color: '#FFFFFF',
    borderColor: '#7DE24E',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 20,
    marginBottom: 20,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
  inputStyle: {
    flex: 1,
    width:300,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    paddingLeft: 25,
    paddingRight: 15,
    borderWidth: 1,
    borderRadius: 30,
    borderColor: 'white',
    fontSize: 16
  },
  registerTextStyle: {
    color: '#FFFFFF',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 15,
  },
  errorTextStyle: {
    color: 'red',
    textAlign: 'center',
    fontSize: 14,
  },
  registerTextStyle1: {
    color: '#4493DC',
    textAlign: 'center',
    fontSize:14,
    fontWeight: 'bold'
  }
});}

This is Screen 2(HomeScreen.js) code where we need to get Data from Screen 1, where we need to display 'firstName' & 'lastName' as "Welcome, Abdul Kalam!".

import { View, Text } from 'react-native';
import axios from 'axios';

const HomeScreen = (props) => {
  global.currentScreenIndex = 'HomeScreen';
  return (
    <View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
      <Text style={{ fontSize: 23, marginTop: 10 }}>Welcome, </Text>
    </View>
  );
};
export default HomeScreen;

It's showing an error as :

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Please help me with this issue, if anyone knows?

1

There are 1 best solutions below

3
On

hi you can store data as async-storage and get it in other screen , or store data with realm Package:)

for set Item:

   try {
      var jsonOfItem = await AsyncStorage.setItem(key, item);
      return jsonOfItem;
    } catch (error) {
      Alert.alert("error", error.message);
      console.log(error.message);
    }

and for get item :

//let bb = await AsyncStorage.getItem('key', value);

if that's helpful , set green checkmark answer for other users:)