sortinousn
sortinousn

Reputation: 647

AsyncStorage.getItem returning undefined when using fetch - React-Native

I'm trying to set a token in my SignIn component using a promise and AsyncStorage but when I go to retrieve the token for use in a different component I get the error Cannot read property 'getItem' of undefined. I tried using Async/Await to wait for the token response in order to save it to storage but i've been getting the same error. How can I properly set the token?

SignIn.js Component

//Function is bound
async signIn() {
const data = JSON.stringify({username: this.state.username, password: this.state.password})

  await fetch(`https://somesecretdomain.com:8443/users/login`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: data
}).then((response) => response.json()).then(async(responseJson) => { 
  AsyncStorage.setItem('jwt', responseJson.id_token);

  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({routeName: 'Profile'})]
  });
  this
    .props
    .navigation
    .dispatch(resetAction);
}).catch((error) => {
  console.warn(error);
})
};

Profile.js Component

async fetchData() {
AsyncStorage
  .getItem('jwt')
  .then((value) => {
    this.setState({"TOKEN": value});
  })
  .done();

console.log(this.state.TOKEN)
const response = await 
fetch(`https://somesecretdomain.com:8443/users/getUsers`, {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'token': this.state.TOKEN
  }
})
const json = await response.json()

}

I changed the Profile.js component to below, still getting the same error.

import React, {AsyncStorage, localStorage} from 'react';
import {
Text,
View,
Image,
TouchableHighlight,
WebView,
TextInput,
KeyboardAvoidingView,
ScrollView
} from 'react-native';

 async fetchData() {
 const TOKEN = await AsyncStorage.getItem('jwt');
 const response = await 
 fetch(`https://somedomain.com:8443/users/getUsers`, {
 method: 'GET',
 headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token' : TOKEN
},
});
const result = await response.json();
  this.setState({data: result})
}

Upvotes: 4

Views: 3656

Answers (1)

yedidyak
yedidyak

Reputation: 1984

Try this:

async signIn() {
    const data = JSON.stringify({username: this.state.username, password: this.state.password})

  const response = await fetch(`https://somesecretdomain.com:8443/users/login`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: data
  });
  const result = await response.json();
  await AsyncStorage.setItem('jwt', result.id_token);

  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({routeName: 'Profile'})]
  });
  this
    .props
    .navigation
    .dispatch(resetAction);
});
};

Upvotes: 2

Related Questions