skip to Main Content

I am trying to set up a session in my react native
I am new to mobile app development. I don’t know whether this is the correct approach to set a session
I am coming from react js background so I tried this approach but in the application tab in react native debugger I dont find the session token set can someone explain and help me whether this is a correct approach

  axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/register',
      data: Data56,
    });
    .then(function (response) {
           storeData(response.data.token);
          alert('sucess');
      .catch(error => {
      alert(JSON.stringify(error.response, 'catch'));
      });
  }

5

Answers


  1. first install

         npm install react-client-session --save
    

    Then

    import { ReactSession } from 'react-client-session';
    
    
    function Login() {
       ReactSession.setStoreType("localStorage");
       ReactSession.set("username", "Meon");
    
       return (
          <div>
           <Switch>
            // Routes 
           </Switch>
        </div>
       );
      }
    
       export default Login;
    

    Then Call your session anywhere as like this

        const loggedIn = ReactSession.get("username");
    
    Login or Signup to reply.
  2. You can use @react-native-async-storage/async-storage library for storing your AUTH_TOKEN. Here is the code with explanation.

    When user login your api would return a token that you can store the in the AysncStorage.

    const storeData = async (value) => {
      try {
        await AsyncStorage.setItem('auth_token', value)
      } catch (e) {
        // saving error
      }
    }
    

    and with this function you can get your token.

    const [auth_token, setAuthToken ] = useState(null); 
    const getData = async () => {
      try {
        const value = await AsyncStorage.getItem('auth_token')
        if(value !== null) {
          setAuthToken(value)
        }
      } catch(e) {
        // error reading value
      }
    }
    

    Here you can use it like this.

     axios
          .post('http://10.0.2.2:8000/api/register', Data56)
          .then(function (response) {
             storeData(réponse.token)
          })
          .catch(error => {
          alert(JSON.stringify(error.response, 'catch'));
          });
      }
    

    After you set your token , on the start of the application get the token and store it the redux-store. of the token is null redirect user to login else redirect to Home Screen .

    on API call use can use that token like this.

    var config = {
      method: 'post',
      url: 'https://my.api.url.com//v1/delete_user_account.php?id=98744',
      headers: { 
        'Authorization': `Bearer ${auth_token}`, 
        'Content-Type': 'application/json'
      },
      data : data
    };
    
    axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
    
    Login or Signup to reply.
  3. Here is the code where you can store a token and get that token back.

    import AsyncStorage from '@react-native-async-storage/async-storage';
    import React from 'react';
    import {Text, TouchableOpacity, View} from 'react-native';
    import {SafeAreaProvider} from 'react-native-safe-area-context';
    const App = () => {
      const auth_session_token = 'AwdcE39dsC#43d@2023jlkre2DWjKLD';
      const store_token = (async = value => {
        AsyncStorage.setItem('token', `${value}`)
          .then(() => {
            alert('token is stored');
          })
          .catch(err => {
            alert('some Error', JSON.stringify(err));
          });
      });
    
      const get_auth_token = () => {
        AsyncStorage.getItem('token')
          .then(token => {
            console.log(token);
            alert(JSON.stringify(token));
          })
          .catch(err => {
            console.log('Some Eorr');
            alert('THere is some error', JSON.stringify(err));
          });
      };
      return (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <TouchableOpacity
            onPress={() => store_token(auth_session_token)}
            style={{
              width: 200,
              height: 50,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#0090FF',
            }}>
            <Text style={{color: '#fff', fontWeight: 'bold'}}>Store Token</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => get_auth_token()}
            style={{
              width: 200,
              height: 50,
              marginTop: 60,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#0090FF',
            }}>
            <Text style={{color: '#fff', fontWeight: 'bold'}}>Get Token</Text>
          </TouchableOpacity>
        </View>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  4. While handling tokens it’s better to use react-native-keychain. It is more secure than async storage and better for storing sensitive data.

    install and import keychain :

    npm i react-native-keychain --legacy-peer-deps
    
    import * as Keychain from 'react-native-keychain';
    

    In your case try this approach :

    axios({
        method: 'POST',
        url: 'http://127.0.0.1:8000/api/register',
        data: Data56,
      });
      .then(async function (response) {
            storeData(response.data.token);
            await Keychain.setGenericPassword(response.data.token);
            alert('sucess');
        .catch(error => {
        alert(JSON.stringify(error.response, 'catch'));
        });
    }
    

    If your tokens are not strings and you need to store an Object, just stringify them using

    JSON.stringify(response.data.token)
    

    and retrieve the token anywhere using :

    const token = await Keychain.getGenericPassword();
    

    You can also reset a session easily using :

    await Keychain.resetGenericPassword();
    
    Login or Signup to reply.
  5. Here is simple way using the Async Storage it’s similar window.localStorage.

    Install React Native Async Storage

    npm install @react-native-async-storage/async-storage --save
    

    Now make a api helper name with api.js

    import AsyncStorage from '@react-native-async-storage/async-storage'
    import axios from 'axios';
    export let BASE_URL = 'http://127.0.0.1:8000/api/'
    export let GET = async (params)=>{
    let token = await AsyncStorage.getItem('@token')
    return axios({method:'GET', url:BASE_URL+params, 
        headers: {
          Authorization: token, //here use Bearer token with prefix
        }
      })
    }
     export let POST = async (endpoint,params)=>{
    let token = await AsyncStorage.getItem('@token')
    return axios({
        method:'POST', 
        url:BASE_URL+endpoint, 
        headers: {
          Authorization: token, //here use Bearer token with prefix
        }, 
        data:JSON.stringify(params)
      })
    }
    

    Now store the token into the Async Storage

     import {POST} from "./helper/api"
     import AsyncStorage from '@react-native-async-storage/async-storage'
          POST('register',Data56).then(function (response) {
            AsyncStorage.setItem('@token',response.data.token)
            alert('sucess');
        }).catch(error => {
          alert(JSON.stringify(error.response, 'catch'));
        });
       }
    

    After the storing a token in async storage next api will call with auth token

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search