How to use AsyncStorage to store array in React Native - react-native

I am trying to use AsyncStorage to store simple Profile using React Native.
Here is What I have so far for adding Profile, I tried console.log(contact), but showed nothing.
function AddContact(props) {
const [FName,setFName] = useState('');
const [LName,setLName] = useState('');
const [PNumber,setPNumber] = useState('');
var contact = {
firstname : FName,
lastname : LName,
phonenumber : PNumber
};
const storeContact = async() => {
try {
await AsyncStorage.setItem(
'#MySuperStore:key', JSON.stringify(contact));
} catch (error) {
// Error saving data
}}
For Loading Profile
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key', JSON.stringify(contact));
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
Please help.

In order to load the data from the Async Storage, your loadContact method should be:
For Loading Profile
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
const json = JSON.parse(value); // this is how you get back the array stored
if (json !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};

AsyncStorage.getItem() only accept one argument that is key. So you have to pass only argument "key" and it will return your data as string:
const value = await AsyncStorage.getItem('#MySuperStore:key');
Or if you want to use this value as array to display something you have to convert it into json.
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null) {
// We have data!!
console.log(value);
this.setState({
data: JSON.parse(value);
});
}
} catch (error) {
// Error retrieving data
}
};

Related

unable to read object (Can't find variable error)

In my below code, I stored an object in AsyncStorage in React Native, but I have a problem reading it inside {personValue}. I got
Can't find variable personValue
Error. could you help me to run my code?
const storeData = async () => {
try {
const newperson = JSON.stringify(person);
await AsyncStorage.setItem("#Key", newperson);
alert(newperson);
} catch (e) {
}
};
const getData = async () => {
try {
const personValue = await AsyncStorage.getItem("#Key");
if (personValue !== null) {
console.log(JSON.parse(personValue));
return JSON.parse(personValue);
}
} catch (error) {
}
in the console, I can see the object correctly in GetData method
P.S: I found the mistake I made. I parsed the wrong variable.
const getData = async () => {
try {
const personValue = await JSON.parse(AsyncStorage.getItem("#Key"));
if (personValue !== null) {
console.log(personValue);
return personValue;
}
}

Invalid key provided to SecureStore. Keys must not be empty and contain only alphanumeric characters, ".", "-", and "_"

I keep getting this error after changing from AsyncStorage to Expo SecureStore,
Invalid key provided to SecureStore. Keys must not be empty and contain only alphanumeric characters, ".", "-", and "_".
I do not know how exactly to solve it. Could it be the + operator I used to concatenate the
I suspect the error is here or:
import * as SecureStore from "expo-secure-store";
import dayjs from "dayjs";
const prefix = "cache";
const expiryInMinutes = 5;
async function store(key, value) {
try {
const item = {
value,
timestamp: Date.now(),
};
const prefixkey = prefix + key;
await SecureStore.setItemAsync(prefixkey, JSON.stringify(item));
} ...
}
}
async function get(key) {
try {
const prefixkey = prefix + key;
const value = await SecureStore.getItemAsync(prefixkey);
const item = JSON.parse(value);
if (!item) return null;
if (isExpired(item)) {
await SecureStore.deleteItemAsync(prefixkey);
return null;
}
return item.value;
} catch ...
}
}
export default {
store,
get,
};
or here:
import * as SecureStore from "expo-secure-store";
import jwtDecode from "jwt-decode";
const key = "authToken";
const storeToken = async (authToken) => {
try {
await SecureStore.setItemAsync(key, authToken);
} catch (error) ...
};
const getToken = async () => {
try {
return await SecureStore.getItemAsync(key);
} catch ...
}
};
const getUser = async () => {
const token = await getToken();
return token ? jwtDecode(token) : null;
};
const removeToken = async () => {
try {
await SecureStore.deleteItemAsync(key);
} catch ...
}
};
export default { getToken, getUser, removeToken, storeToken };
Thank you.

React Redux rejectWithValue() not working

I'm currently facing a problem, when I try to reject a value when my node-fetch request fail, thunkApi.rejectWithValue() isn't working. However when my request is pending or when It's fulfilled, It's working fine.
Here's my slice :
export const userSlice = createSlice({
name: "user",
initialState: initialState as User,
reducers: {
...
},
extraReducers: (builder) => {
...
builder.addCase(changePassUser.pending, (state) => {
GGLog("FETCHING CHANGEPASS API...");
state.isFetching = true;
return state;
});
builder.addCase(changePassUser.fulfilled, (state, { payload }) => {
GGLog("FULFILLED CHANGEPASS:", JSON.stringify(payload));
state.isFetching = false;
state.isSuccess = true;
state.isError = false;
return state;
});
// eslint-disable-next-line #typescript-eslint/no-explicit-any
builder.addCase(changePassUser.rejected, (state, { payload }: any) => {
GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));
state.isFetching = false;
state.isError = true;
state.errorMessage = payload.data;
return state;
});
},
});
Here's my thunk :
export const changePassUser = createAsyncThunk(
"users/password/update",
async ({ oldpassword, newpassword }: RegisterParameters, thunkAPI) => {
try {
const res = await changePassApi.changePass.return({
oldpassword: oldpassword,
newpassword: newpassword,
});
GGLog("API_CHANGEPASS_RES:", res);
const data = await res.json();
if (res.ok) {
GGLog("API_DATA_RESPONSE_OK: ", data);
const tokenData = JSON.stringify(res.headers);
const token = JSON.parse(tokenData).map["x-auth"];
await localStorage.store("token", token);
return data;
} else {
GGLog("API_DATA_RESPONSE_NOK: ", data);
return thunkAPI.rejectWithValue(data);
}
} catch (e) {
GGLog("Error while fetching Login API => ", e);
return thunkAPI.rejectWithValue(e);
}
}
);
And here's the result in the console :
Console output
Any ideas ? Am I missing something ?
Thanks :)
Okay I've found my problem, I was just focused on the thunk and didn't pay attention to the promise rejection. I was trying to parse a JSON that does'nt exist... Just remove the GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));in the slice.
It's working fine now !

Using AsyncStorage to show screen on first login

I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});

React native AsyncStorage bad response

Have created React Native app and ned to use AsyncStorage to benefit from it's storage mechanism.
To save in AsyncStorage use code:
_storeData = async (param) => {
try {
let par = JSON.stringify(param);
//await AsyncStorage.setItem(this.key, par);
Utilities.setItem(this.key, par);
this._retrieveData();
} catch (error) {
console.log(JSON.stringify(error));
}
};
To retrieve data:
_retrieveData = async () => {
try {
const value = Utilities.getItem(this.key);
if (value !== null) {
alert('data is new: ' + JSON.stringify(value));
}
} catch (error) {
}
};
And, to setItem and getItem in Utilities partial:
const setItem = (key, value) => {
if (!key || !value) return;
AsyncStorage.setItem(key, value);
};
const getItem = (key) => {
if (!key) return;
var val = AsyncStorage.getItem(key);
return val;
};
Data is being saved, but response I'm getting does not look correctly, as it's a string of 'weird' characters:
{"_40":0,"_65":0,"_55":null,"_72":null}
Does anybody know why I'm getting such answer?
Note that AsyncStorage.getItem is also async - the weird characters represent the promise being returned by getItem.
Use var val = await AsyncStorage.getItem(key); and mark your getItem utility function as async. You'll need to await on any calls to Utilities.getItem and Utilities.setItem as well.