JWT TOKEN authentication is not persisting

Asked

Viewed 400 times

-1

Well, every time I Reload in my application or open and close it, I have to put the login and password, it could be some error in my code, could someone take a look? 'Cause I need when I open do Reload no need to enter password and email.

import axios from 'axios';

import { AsyncStorage } from 'react-native';

const api = axios.create({
  baseURL: 'http://10.0.3.2:3333/',
});

api.interceptors.request.use(async (config) => {
  try {
    const token = await AsyncStorage.getItem('@App:token');

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  } catch (err) {
    alert(err);
  }
});

export default api;

2 answers

0

You can try using this example code

import AsyncStorage from "@react-native-community/async-storage";
import { create } from "apisauce";
import { Constants } from "../constants";
import Reactotron from 'reactotron-react-native'
const api = create({
  baseURL: Constants.API_BASE_URL,
  timeout: 3000
});

api.addAsyncRequestTransform(request => async () => {
  const token = await AsyncStorage.getItem("@omnix:token");

  if (token) {
    request.headers["Authorization"] = `Bearer ${token}`;
  }
});

api.addResponseTransform(response => {
  if (!response.ok) throw response;
});

export default api;

Just one note, the Asyncstore will be removed from the React Native core, upgrade to the React-Native-community repository

  • Will Asyncstore be removed from React-Native? From now on you will have to use libraries?

  • Yes, it will be replaced by the repository at https://github.com/react-native-community/react-native-async-storage

0

Cassio, this component of yours seems right to me. The question is how you are doing this check on the input component. As if it were so:

import React, { Component } from 'react'
import { AsyncStorage } from 'react-native'

export default class App extends Component {
  state = {
    hasChecked: false,
    hasUser: false
  };

  async componentDidMout() {
    const user = await AsyncStorage.getItem('SeuUsuario');
    this.setState({
      hasChecked: true,
      hasUser: !!user,
    })
  }
  // Aqui no render a gente vê se foi checado. Se sim você repassa pra suas rotas que
  // está logado ou não e exibe o login ou a home do seu projeto
  render() {
    if (!this.state.hasChecked) return null;

    return(
      <Routes hasUser ={this.state.hasUser} />
    );
  }
}

Na in your route component you check if hasUser came TRUE if yes, it shows Home, if it does not show Login. I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.