How to store API data in app after login into an app and use it after in another screen in react native

那年仲夏 提交于 2021-02-11 12:20:40

问题


I am new to react native. I have created An app. In this app when User login he get a data through API. for example = userID = 1, userName = abc. so I want to save that data in session storage or local storage in app. and I want to use it after for posting my form data to server. for example when user looged in he get ID that is 1 and when It goes to Form screen and submit the form then. I want to send that userID through API to server means in database.

here is my login screen

import React, { Component } from "react";
import {
  Dimensions,
  ActivityIndicator,
  Keyboard,
  Image,
  KeyboardAvoidingView,
  StyleSheet,
  Alert,
  View,
  SafeAreaView,
  TextInput
} from "react-native";

import { Button, Block, Input, Text } from "../components";
import { theme } from "../constants";
import { StackNavigator } from "react-navigation";

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",
      loading: false,
      errors: [],
      data: "",
      first_name: "",
      message: "",
    };
  }

  validate = (text) => {
    // console.log(text);
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (reg.test(text) === false) {
      console.log("Email is Not Correct");
      <Text>error</Text>
      this.setState({ email: text })
      return false;
    }
    else {
      this.setState({ email: text })
      console.log("Email is Correct");
    }
  }

  handleLogin() {
    const { username, password } = this.state;
    fetch("https://xyz.tech/Android_API_CI/login_details", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify([{ username: username, password: password }]),
    })
      .then((returnValue) => returnValue.json())
      .then((response) => {
     
        //login to check details from server and then display or navigate to another screen
        if (
          response &&
          response.length &&
          response[0].message != "error"
          //&& response != "error"
        ) {
          
          alert(JSON.stringify(response))
          this.props.navigation.navigate("Drawer", {
            Email: username,
            Password: password,
            //data: respose.first_name,
          });
        } else {
          alert("Cehck Details");
        }
      })
      .catch((error) => alert("Cehck Details"));
  }
  render() {
    const { navigation } = this.props;
    const { loading, errors } = this.state;
    const hasErrors = (key) => (errors.includes(key) ? styles.hasErrors : null);
    const offset = (Platform.OS === 'android') ? -200 : 0;

    return (
      <KeyboardAvoidingView keyboardVerticalOffset={offset} style={styles.login} behavior="padding" >
        <View style={styles.container}>
          <Image
            source={require("../assets/nas_dig_logo-removebg.png")}
            resizeMode="contain"
            // onLayout={this.onLayout}
            style={{
              flex: 1,
              // width: this.state.width,
              // height: this.state.height,
              width: 300,
              height: 200,
              alignItems: "center",
              justifyContent: "center",
              height: (Platform.OS === 'android') ? 150 : 200,
              width: (Platform.OS === 'android') ? 250 : 300, 
            }}
          />
        </View>
        <Block padding={[0, theme.sizes.base * 2]}>
          <Block middle>
            <Input
              label="Email"
              // error={hasErrors("email")}
              // style={[styles.input, hasErrors("email")]}
              defaultValue={this.state.username}
              onChangeText={(userInputedText) =>
                this.setState({ username: userInputedText })
              }
            />
            <Input
              secure
              label="Password"
              // error={hasErrors("password")}
              // style={[styles.input, hasErrors("password")]}
              defaultValue={this.state.password}
              onChangeText={(text) => this.setState({ password: text })}
            />
            <Button gradient onPress={() => this.handleLogin()}>
              {loading ? (
                <ActivityIndicator size="small" color="white" />
              ) : (
                <Text bold white center>
                  Login
                </Text>
              )}
            </Button>

            {/* <Button onPress={() => navigation.navigate("Forgot")}>
              <Text
                gray
                caption
                center
                style={{ textDecorationLine: "underline" }}
              >
                Forgot your password?
              </Text>
            </Button> */}
          </Block>
        </Block>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  login: {
    flex: 1,
    justifyContent: "center",
  },
  input: {
    borderRadius: 0,
    borderWidth: 0,
    borderBottomColor: theme.colors.gray2,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  hasErrors: {
    borderBottomColor: theme.colors.accent,
  },
  container: {
    flex: 1,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    marginBottom: -100,
    marginTop: -80,

    ...Platform.select({
      android: {
        marginBottom: -80,
      },
    }),
  },
});

and here is my form screen

//Picker has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from @react-native-community/picker instead of 'react-native'.


import React, {useState, Component} from 'react';
import { Text, StyleSheet, View, TextInput, Button, KeyboardAvoidingView, ScrollView, alert, Alert, Platform} from 'react-native';
import DatePicker from 'react-native-datepicker';
import {Picker} from '@react-native-community/picker'
//import picker from '@react-native-picker/picker';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
// import DateTimePicker from '@react-native-community/datetimepicker';
import DropDownPicker from 'react-native-dropdown-picker';
import { Ionicons } from '@expo/vector-icons';
import { BackHandler } from 'react-native';

    //  const [date, setDate] = useState('09-10-2020');
    //  const offset = (Platform.OS === 'android') ? -200 : 0;
    //  const [nature, setnature] = useState('Public'); 

 class PickerDemo extends Component{

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
 }
 
 componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
 }
 
 handleBackButtonClick() {
   this.props.navigation.navigate("FormItems");
   return true;
 }

  constructor(props) {
    super(props);
    this.state={
      Place:"",
      Distributor:"",
      DistributorCode:"",
      SalesCode:"",
      date: '09-10-2020',
      mode: 'date',
      show: 'false',
      nature: 'public',
    };
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }

validateInputs = (event) => {



  //  if (!this.state.accountNo.trim()) 
  if (!this.state.Place.trim()) 
  {
    this.setState({ PlaceError: 'Field Should Not Be An Empty' })
    return;
  }
  if (!this.state.Distributor.trim()) 
  {
    this.setState({DistributorError: 'Field Should Not Be An Empty' })
    return;
  }
  if (!this.state.DistributorCode.trim()) 
  {
    this.setState({ DistributorCodeError: 'Field Should Not Be An Empty' })
    return;
  }
  if (!this.state.SalesCode.trim()) 
  {
    this.setState({ SalesCodeError: 'Field Should Not Be An Empty' })
    return;
  } 
    else {
          //+++++++++++++++++++++++++++++++++=submitting form data to api start+++++++++++++++++++++++++++++++++++
 
{
  // Alert.alert('A form was submitted: ' + this.state);
  
  const { Place, date, nature, Distributor, DistributorCode, SalesCode } = this.state;
  fetch('https:/zyz.tech/Android_API_CI/uploaddata/_retail_details', {
      method: 'POST',
      headers: { "Content-Type": "application/json" },
      // We convert the React state to JSON and send it as the POST body
      body: JSON.stringify([{name_of_place : Place, captured_date: date, nature_of_business: nature, dist_name:  Distributor, dist_code:  DistributorCode, sales_team_code: SalesCode, created_time: $timestamp, entry_sorce: "app",created_by:"user1", application_id:"1", is_active:"Y",is_deleted:"N" }])
    })
    .then((returnValue) => returnValue.json())
    .then(function(response) {
      console.log(response)
      return response.json();
    });
  // event.preventDefault();
  }
  //+++++++++++++++++++++++++++++++++submitting form data to api end++++++++++++++++++++++++++++++++++++++

      Alert.alert("All fields validated")
      return;

    }

  }



  handlePlace = (text,event) => {
    // this.setState({[event.target.Place]: event.target.value});
    this.setState({ PlaceError: '' })
    this.setState({ Place: text })
  }
  handleDistributor = (text) => {
    this.setState({ DistributorError: '' })
    this.setState({ Distributor: text })
  }
  handleDistributorCode = (text) => {
    this.setState({ DistributorCodeError: '' })
    this.setState({ DistributorCode: text })
  }
  handleSalesCode = (text) => {
    this.setState({ SalesCodeError: '' })
    this.setState({ SalesCode: text })
  }

render(){
  const offset = (Platform.OS === 'android') ? -200 : 0;
  const { navigation } = this.props;

  return (
    <View style={{flex: 1}}>
      
      <View style={styles.header}>
       <Ionicons style={{paddingLeft:20}} name="arrow-back" size={40} 
      color="black"  onPress={() => navigation.navigate("FormItems")} />
      <Text style={{fontSize:20, paddingLeft: 70, paddingTop: 10}}>Retail Information</Text>
      </View>

    <KeyboardAvoidingView keyboardVerticalOffset={offset} style={styles.form} behavior='padding'>

      <Text style={styles.formLabel}> Retail Information Form </Text>

      <ScrollView style={{flex: 1,}} showsVerticalScrollIndicator={false}>

         <TextInput  maxLength={50} placeholder="Place" style={styles.inputStyle}
         onChangeText={this.handlePlace} defaultValue={this.state.Place}  />
         <Text>{this.state.PlaceError}</Text>

         <DatePicker
         style={styles.datePickerStyle}
        date={this.state.date}
        mode="date"
        placeholder="select date"
       format="YYYY-MM-DD"
        // format="DD-MM-YYYY"
        // minDate="01-05-2016"
        // maxDate="01-06-2050"
        minDate="2011-05-20"
        maxDate="2050-06-20"
        confirmBtnText="Confirm"
        cancelBtnText="Cancel"
        customStyles={{
          dateIcon: {
            position: 'absolute',
            left: 0,
            top: 4,
            marginLeft: 0
          },
          dateInput: {
            marginLeft: 36,
            borderWidth: 0
          }
          // ... You can check the source to find the other keys.
        }}
        defaultValue={this.state.date}
        onDateChange={(date) => {this.setState({date: date})}}
      />
      <Text></Text>
        <DropDownPicker 
    items={[
        {label: 'public', value: 'public'},
        {label: 'government', value: 'government'},
        {label: 'private', value: 'private'},
    ]}
    defaultValue={this.state.nature}
    containerStyle={{height: 40, flex:1, }}
    style={{backgroundColor: '#fafafa',}}
    itemStyle={{
        // justifyContent: 'flex-start',
    }}
    dropDownStyle={{backgroundColor: '#fafafa',}}
    onChangeItem={item => this.setState({
        nature: item.value
    })}
/>

        <TextInput  maxLength={20} placeholder="Distributor Name" style={styles.inputStyle} 
         onChangeText={this.handleDistributor} defaultValue={this.state.Distributor}  />
         <Text>{this.state.DistributorError}</Text>

        <TextInput  maxLength={3} keyboardType = 'numeric' placeholder="Distributor Code *" style={styles.inputStyle} 
         onChangeText={this.handleDistributorCode} defaultValue={this.state.DistributorCode} />
         <Text>{this.state.DistributorCodeError}</Text>

        {/* <View style={styles.inputStyle}> */}
      
        {/* </View> */}
        <TextInput  maxLength={3} keyboardType = 'numeric' placeholder="Sales Team Code " style={styles.inputStyle} 
         onChangeText={this.handleSalesCode} defaultValue={this.state.SalesCode} />
         <Text>{this.state.SalesCodeError}</Text>

        </ScrollView>
        <View style={{ height: 30 }} />
       
        <Button style={styles.inputStyleB}
          title="Submit"
          color="#808080"
          onPress={() => this.validateInputs()}
        />
         </KeyboardAvoidingView>
         </View>
  );
};
}

const styles = StyleSheet.create({
  datePickerStyle: {
    marginTop: 20,
    width: 300,
    height: 40,
    paddingHorizontal: 10,
    borderRadius: 1,
    backgroundColor: 'rgb(255, 252, 252)',
    
  },
  form: {
    flex: 1,
    justifyContent: "center",
    flex: 1,
    backgroundColor: "rgb(247, 146, 57)",
    alignItems: 'center',
    paddingTop: 50,
  },
  container: {
    flex: 1,
    backgroundColor: "rgb(247, 146, 57)",
    alignItems: 'center',
    // justifyContent: 'center',
    paddingTop: 15,
  },

  formLabel: {
    fontSize: 20,
    color: 'rgb(10, 10, 10)',
  },
  inputStyle: {
    marginTop: 20,
    width: 300,
    height: 40,
    paddingHorizontal: 10,
    borderRadius: 1,
    backgroundColor: 'rgb(255, 252, 252)',
  },
  formText: {
    alignItems: 'center',
    justifyContent: 'center',
    color: '#fff',
    fontSize: 20,
  },
  text: {
    color: '#fff',
    fontSize: 20,
  },
  
  header:{
    flexDirection: 'row'
  }
});

export default PickerDemo;

回答1:


AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the application. It should be used instead of LocalStorage.

Importing the AsyncStorage library:

import { AsyncStorage } from 'react-native';

You can set an item in the storage of your application. if your value is number (integer) formate then you need to convert your number (integer) value into the string otherwise don't need to convert.

const stringID= userID.toString();
     AsyncStorage.setItem(
      "stringIDKey",
      stringID
     ).then(() => console.log("userID save"));

And you can get item from the storage of your application. now the value is set as string formate so we need to convert the value into the number(integer).

AsyncStorage.getItem("userID").then((result) =>
  console.log(Number(result));
 );

In the end, if you need more help this link will help you



来源:https://stackoverflow.com/questions/66124183/how-to-store-api-data-in-app-after-login-into-an-app-and-use-it-after-in-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!