Swix
Swix

Reputation: 2123

How to manage user session in React Native?

I'm learning React Native with React Navigation and GraphQL written in TypeScript. I will use Facebook Login for users to register (with Passport.js or Auth0)

How do I manage user session in React Native? Do I need to use Redux?

Please enlighten me.

Upvotes: 2

Views: 23667

Answers (3)

I Putu Yoga Permana
I Putu Yoga Permana

Reputation: 4220

Because session usually contains sensitive info, I would advise avoiding using AsyncStorage or similar solution.

Use more secure approach with react-native-keychain. It will store the session on secure storage.

Sample Code

import * as Keychain from 'react-native-keychain';

// When you want to store the session
const rawValue = JSON.stringify(session);
await Keychain.setGenericPassword('session', rawValue);

// When you want to retrieve the session
const credential = await Keychain.getGenericPassword();
const session = JSON.parse(credential.password)

Upvotes: 7

Majid Lotfinia
Majid Lotfinia

Reputation: 714

you can add user session in redux and persist your redux data with redux-persist.

so add user session info to api call header each time when you call remote endpoint

Upvotes: 0

Mehran Khan
Mehran Khan

Reputation: 3636

You can save user session(data) using AsyncStorage . Please try this library async-storage as recommended By React Native Website

Store data

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

Read data

getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

Upvotes: 1

Related Questions