score:4
here is a localstorage wrapper i wrote not so long ago, it also includes the functionality to set ttl on an object/key if you need an expiration date behavior, i use it for the same logic as you do, which is to check if there is a saved token and navigate to the main app view instead of the login page.
here is the wrapper:
// rn < 0.59
import { asyncstorage } from 'react-native'
// rn > 0.59
import asyncstorage from '@react-native-community/async-storage';
/**
*
* @param key key value of the object to be saved
* @param object the object to save
* @param ttl (optional) set an expiration date on an object in ms
* @return {promise<void>}
*/
export const setobjectforkey = async ({key, object, ttl = undefined }) => {
if (!key) throw new error('cannot set an object without a key');
if (!object) throw new error('cannot set a key without an object');
let expiresat = undefined;
if (ttl) {
expiresat = new date().gettime() + ttl;
}
let wrappedobj = {
object,
expiresat,
};
let stringedwrapper = json.stringify(wrappedobj);
return await asyncstorage.setitem(key,stringedwrapper)
};
/**
*
* @param key the key of the object to remove
* @return {promise<void>}
*/
export const removeobjectforkey = async (key) => {
return await asyncstorage.removeitem(key)
};
/**
*
* @param key the key of the object to retrieve
* @return {promise<*>}
*/
export const getobjectforkey = async (key) => {
let now = new date().gettime();
let stringedwrapper = await asyncstorage.getitem(key);
if (!stringedwrapper) throw new error('no key found for object');
let wrapper = json.parse(stringedwrapper);
if (wrapper.expiresat < now) {
// object expired
asyncstorage.removeitem(key);
throw new error('object expired');
} else {
return wrapper.object;
}
};
and here is a usage example (in my solution i have a redux middleware so after i retrieve an object i call dispatch):
get:
let key = 'app_token';
localstorage.getobjectforkey(key)
.then((retrievedobject) => {
// do what you want with object
})
.catch((err) => {
// handle error, object either doesn't exist, expired or a system error
})
set:
let key = 'app_token';
let object = {token: 'jwt_hash'};
let ttl = undefinded // ttl is optional
localstorage.setobjectforkey({
key,
object,
ttl,
})
.then(() => {
// set was successfull
})
.catch((err) => {
// handle error
})
delete:
localstorage.removeobjectforkey(key)
.then(() => {
// successfully deleted
})
.catch((err) => {
// object either doesn't exist to delete or system error
})
notice that i actually save objects that i stringify, so even if i'm save the api token, i actaully save an object with a token as a key, i.e: {token: 'token'}
hope that helps
update 2019-06-06
as of react-native
0.59
, the asyncstorage module is deprecated due to the efforts to make react-native
's core library thinner... the asyncstorage should now be installed through @react-native-community/react-native-async-storage
score:2
/* login screen */
async storesessiontoken(token) {
try {
await asyncstorage.setitem('token', token);
console.log("data saved successfully");
// rest of your code
} catch (error) {
console.log("error while storing the token");
}
}
/* splash screen */
async retrievesessiontoken() {
try {
const token = await asyncstorage.getitem('token');
if (token !== null) {
console.log("session token",token );
return token;
}
} catch (error) {
console.log("error while storing the token");
}
}
// calling retrievesessiontoken
componentdidmount() {
this.retrievesessiontoken()
.then((token)=> {
if(token) this.setstate({token: token})
})
}
Source: stackoverflow.com
Related Query
- retrieve data from asyncStorage in react native
- How to Cache API data using AsyncStorage React Native
- Storing Value from JSON response to AsyncStorage React Native
- Differentiate between the previous element and current element from the data of a Flatlist in react native
- `fetch` in React Native doesn't return expected data from URL
- React native Material drop down get id from json data
- How to retrieve data from custom attribute on option tag in React
- How to retrieve data from promise object in React JS
- React Native release apk does not fetch data from local network
- How do I configure axios in react to retrieve data with an objects id from an api?
- can't seem to retrieve data from this api in react
- Express Js is unable to retrieve submitted form data from React Js
- Extracting data from json object from API with JavaScript React Native
- React Native Fetch data from API - BUT not render in flat list, just single time
- React native : What is the way to take data from 1 function and pass it to function number 2?
- cannot retrieve data from react axios post to express node, tried all I could find
- I do not know how to store json data from an api call within a nodejs express server, and send it to a react native client
- Retrieve data from array.map via onClick in react
- Rendering data from fetch request React Native
- Data obtained from Firebase Realtime Database in React Native using Hooks is not displayed on the screen
- Retrieve data and display from two different table/lists in react sharepoint
- I'm using React to retrieve data from Firebase, but the userItem is not defined in my render function why
- What is the problem in React hook when retrieve data from API
- retrieve store data from react redux
- How to apply the AsyncStorage to React Native app for storing data on TextInput and Picker
- Cannot retrieve data from provider/reducer when route is manually typed in React
- How to show markers on map fetching data from a JSON file on React Native
- Fetch data from multiple pages of an API in react native
- How to retrieve data in PHP, sent from React js using fetch()?
- trying to fetch data from api and show it in react native flatlist and my code displays data in console log,but it didnt render in emulator
More Query from same tag
- Reactjs - Playing audio files from outer folder in local machine
- How I can access the values from a form made via Reactbootstrap when a user clicks submit button, am I unable to grab the values
- React TypeError: Class constructor Fullpage cannot be invoked without 'new'
- Jest TypeError: redux action creator is not a function
- How to get actual Dom node with React.useRef ? Element.getBoundingClientRect() not working on useRef variable
- Incompatible types between SVGPathElement and <path> when using spread operator React Typescript
- Maximum update depth exceeded while trying to liftup function to child via props
- ReactJS and jest: how to use a mock value for element.offsetWidth?
- am fetching data from firebase but authData is empty when the app renders once
- Round arrow button surrounded with three break steps
- In the tag component I created using AntDesign, the first value of the array comes as an empty string
- Listen for changes in Formik field using ref and useEffect
- How to declare a property with a dependency of other property in state constructor of React?
- add multiple node box selector on the canvas of VisJS network graph in ReactJS
- Page is rendering but not components although everything compiles and styles can be added outside the component
- Argument of type is not assignable to type ObservableInput<any>
- How to set up dynamic row height in react-virtualized List?
- Reactjs + Material-ui , checkboxes not working
- React, button with link and onClick
- Webpack 5 Receiving a Polyfill Error?!?! My JavaScript React project is receiving a polyfill error while trying to compile my webpack.config.js file
- What is the exact usage of componentWillUpdate in ReactJS?
- Javascript code works in Chrome, but not in other browsers
- React - pass state to Route
- How to set some value in express backend server.js file and use it in create-react-app code?
- RTCRecorder: TypeError Recorder is not a constructor
- OnClick in react portal works only after second click
- Using jest-dom matchers with puppeteer objects
- How to stop a css animation in react
- How can I get a specific key value from another schema, By comparing if they have same key value?
- js/react: sync call in event handler works, but async call does not