Search code examples
react-nativeauthenticationstoreasyncstorage

How to keep user logged in (store userId with AsyncStorage)


I am able to Login using my username and password (hardcoded), however, after login in I want to fetch some data from an API which can be done only if I am authenticated. So, the question is how can I keep the user logged in?

I am not that good in React-Native so any help would be highly appreciated!

Here is my code:

import React, { Component } from 'react';
import { Text, View, StyleSheet,AsyncStorage, FlatList, AppRegistry } from 'react-native';
import { ListItem } from 'react-native-elements';


export default class BMPServer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       username: 'testuser', 
       password: 'mypasswordhere',
       signedIn: false,
      checkedSignIn: false 
      };


    this.getAllDocuments();

 }
getAllDocuments = () => {

  fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              username : this.state.username,
              password : this.state.password,
            })
          }) 

        .then((response) => response.json())

      .then((responseDocs) => {

        console.log("YOU HAVE SUCCSFULLY LOGGED IN:", responseDocs) 

});}

Solution

  • I have found out a solution to my problem. Fetch() sets cookies automatically but you have to include this when fetching: credentials: 'include'. There is no need for AsyncStorage or anything like that, it is just a waste of time and unfortunately even after a week of search about this problem I was not able to find out a solution anywhere on the internet, and obviously the solution is very very simple.

    See code below for details:

    getAllDocuments = () => {
        fetch('LOGIN_URL_HERE', {     //*HERE I AM AUTHENTICATING*
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Connection': 'Keep-Alive',
          },
          body: JSON.stringify({
            username: 'myemail',
            password: 'mypassword'
          })
        })
          .then((response) => response.json())
    
          .then((res) => {
    
            console.log("This is the user:", res)
    
            fetch('DOCUMENTS_URL_HERE', {    //*HERE I AM FETCHING DOCUMENTS AFTER I HAVE SUCCESSFULLY AUTHENTICATED*
              method: 'POST',
              headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
              credentials: 'include',     //USE THIS TO SET COOKIES
              body: JSON.stringify({
                lastServerSyncDateAsLong: 0,
                inserted: {},
                edited: {},
                deleted: {}
              })
            })
         .then((res) => res.json())
    
              .then((ressDocs) => {
                console.log("THESE ARE ALL DOCUMENTS FETCHED FROM API:", ressDocs)
              })
    
          })
    
      }