React Native AsyncStorage not working - now what am I doing wrong? - react-native

What am I leaving out here?
At this point I just want to see it write a value and retrieve a value. By setting the variable "appType" I can see if it's working. It is not because the initial value of "appType" is not changing. I can tell this by which page is loading. I need this information upfront to determine which page is to load first.
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import AsyncStorage from '#react-native-community/async-storage';
import SpMyPage from './screens/s_mypg';
import UsMyPage from './screens/u_mypg';
import UsRegPage from './screens/u_regs';
function checkAsyncStorage(){
var appType = '';
const storeData = async () => {
try {
await AsyncStorage.setItem('random_time', '50000')
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('random_time')
if(value !== null) {
// value previously stored
appType = 'S';
}
else {
appType = 'U';
}
} catch(e) {
// error reading value
appType = 'U';
}
}
return appType;
}
function PreHomeScreen() {
var appType = checkAsyncStorage();
if (appType == 'S') {
return <SpMyPage />;
}
else {
if (appType == 'U') {
return <UsMyPage />;
}
else {
return <UsRegPage />;
}
}
}
/* ************************************************************************** */
const Stack = createStackNavigator();
function App() {
return (
<>
<NavigationContainer>
<Stack.Navigator
initialRouteName = "PreHomeScreen"
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="PreHomeScreen" component={PreHomeScreen} />
<Stack.Screen name="SpMyPage" component={SpMyPage} />
<Stack.Screen name="UsMyPage" component={UsMyPage} />
<Stack.Screen name="UsRegPage" component={UsRegPage} />
</Stack.Navigator>
</NavigationContainer>
</>
);
};
export default App;

I think the right way to import AsynStorage is
import AsyncStorage from '#react-native-community/async-storage';
Here's an example from the repo.
https://github.com/react-native-community/async-storage/blob/master/example/examples/GetSetClear.js

My original goal was to use AsyncStorage.
I coded it the way the examples showed.
But, I found that apparently I don't need to have an "async function" wrapped around the AsyncStorage methods. Hence no "await" needed either. Not sure if this is going to cause a problem but for now it seems to work.
function checkAsyncStorage(){
var appType = '';
try {
AsyncStorage.setItem('random_time', '50000')
} catch (e) {
// saving error
}
try {
const value = AsyncStorage.getItem('random_time')
if(value !== null) {
// value previously stored
appType = 'S';
}
else {
appType = '';
}
} catch(e) {
// error reading value
appType = 'U';
}
return appType;
}

// The import statement should be like:
import AsyncStorage from '#react-native-community/async-storage';
// The function to retrieve previously stored data (In this example it's "userId")
retrieveData = async () => {
try {
const userId = await AsyncStorage.getItem('userId');
if (userId != null) {
console.log(userId);
}
} catch (e) {
console.log(e);
}
};
// The function to store data (In this example it's "userId")
storeData = async () => {
try {
await AsyncStorage.setItem('userId', value);
} catch (e) {
console.log(e);
}
};

Related

Use value from AsyncStorage for VideoThumbnails.getThumbnailAsync

I'm trying to use the expo-video-thumbnails package to generate a thumbnail from a video uri. The video uri is retrieved from async-storage. I get the following error
Argument of an incompatible class: class java.util.HashMap cannot be
passed as an argument to parameter expecting class java.lang.String.
If I use a static video uri, it works fine. I can't seem to get this to work with the value from AsyncStorage. Here's my code:
import React, { useState, useEffect } from 'react';
import { View, Image } from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import * as VideoThumbnails from 'expo-video-thumbnails';
export default function ThumbnailsScreen() {
// video uri
const [videoUri, setVideoUri] = React.useState({});
const getData = async () => {
try {
const value = await AsyncStorage.getItem('#lastRecordedVideo')
if(value !== null) {
setVideoUri(value)
}
} catch(e) {
console.log(e);
}
}
getData();
// thumbnails
const [image, setImage] = useState(null);
const generateThumbnail = async () => {
try {
const { uri } = await VideoThumbnails.getThumbnailAsync(
videoUri,
{
time: 1000,
}
);
setImage(uri);
} catch (e) {
console.warn(e);
}
};
useEffect(() => { generateThumbnail(); }, [])
return (
<View>
{image && <Image source={{ uri: image }} /> }
</View>
)
}

useEffect returns unhandled promise

I have been for several hours trying to get an API to be called in ReactNative useEffect hook. Sometimes when I restart my app the value is resolved. But most of the time, I have an Unhandled promise rejection. I googled and tried various methods. I tried using .then etc.. I just can't figure it out.
import React, { useState, useContext, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, FlatList } from 'react-native';
import { EvilIcons } from '#expo/vector-icons';
import jsonServer from '../api/jsonServer';
const ShowScreen = ({ navigation }) => {
const id = navigation.getParam('id');
const [post, setPost] = useState([]);
const getBlog = async () => {
const result = await jsonServer.get(`http://0.0.0.0/blog/docroot/jsonapi/node/article/${id}`);
return result;
}
useEffect(() => {
async function setToState() {
const val = await getBlog();
setPost(val);
}
setToState();
},[]);
return (
<View>
<Text>Here { console.log(post) }</Text>
</View>
);
};
ShowScreen.navigationOptions = ({ navigation }) => {
return {
headerRight: (
<TouchableOpacity
onPress={() =>
navigation.navigate('Edit', { id: navigation.getParam('id')
})}
>
<EvilIcons name="pencil" size={35} />
</TouchableOpacity>
)
};
};
const styles = StyleSheet.create({});
export default ShowScreen;
What you could do is something like this:
....
....
const [post, setPost] = useState([]);
const [isMounted, setIsMounted] = useState(false);
const getBlog = async () => {
const result = await jsonServer.get(`http://0.0.0.0/blog/docroot/jsonapi/node/article/${id}`);
return result;
}
useEffect(() => {
setIsMounted(true)
async function setToState() {
// using try catch I'm handling any type of rejection from promises. All errors will move to catch block.
try{
const val = await getBlog();
// checking if component is still mounted. If mounted then setting a value. We shouldn't update state on an unmounted component.
if(isMounted){
setPost(val);
}
} catch(err){
console.log("Error", err)
}
}
setToState();
return () => {
// Setting is mounted to false as the component is unmounted.
setIsMounted(false)
}
},[]);
I believe this will solve your Unhandled promise rejection error. Please try if it still doesn't solve the issue will create the same in Sanck.
I think my issue was not just promise, the issue is also seems to be me not handling undefined/null in the state. The below code is working for me.
import React, { useState, useContext, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, FlatList } from 'react-native';
import { EvilIcons } from '#expo/vector-icons';
import jsonServer from '../api/jsonServer';
const ShowScreen = ({ navigation }) => {
const id = navigation.getParam('id');
const [post, setPost] = useState([]);
const getBlog = async () => {
const result = await jsonServer.get(`http://hello.com/jsonapi/node/article/${id}`).then(
res => {
setPost(res)
return res;
}, err => {
console.log(err);
});
}
useEffect(() => {
setPost(getBlog());
},[]);
return (
<View>
<Text>{ post.data ? post.data.data.id : "" }</Text>
</View>
);
};
export default ShowScreen;
Note: I am setting the state in useEffect as well as in the request. I am yet to check if I can just do it once.

Can't I return a form custom error anymore with "Altering the Form Values before Submitting"?

React-admin version 2 used redux-form. Together with the documentation "Altering the Form Values before Submitting" i created a custom button that returns a form error from a custom function, or does a save.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { crudCreate, SaveButton, Toolbar } from 'react-admin';
import { SubmissionError } from 'redux-form';
const myValidate = (values) => {
const errors = {};
if (values.files < 1) errors.files = 'resources.Order.errors.files';
return errors;
};
// A custom action creator which modifies the values before calling the default crudCreate action creator
const saveWithNote = (values, basePath, redirectTo) =>
crudCreate('posts', { ...values, average_note: 10 }, basePath, redirectTo);
class SaveWithNoteButtonView extends Component {
handleClick = () => {
const { basePath, handleSubmit, redirect, saveWithNote } = this.props;
return handleSubmit(values => {
return new Promise((resolve, reject) => {
const errors = myValidate(values);
if (errors) {
reject(new SubmissionError(errors))
} else {
resolve( saveWithNote(values, basePath, redirect) );
};
}
});
});
};
render() {
const { handleSubmitWithRedirect, saveWithNote, ...props } = this.props;
return (
<SaveButton
handleSubmitWithRedirect={this.handleClick}
{...props}
/>
);
}
}
const SaveWithNoteButton = connect(
undefined,
{ saveWithNote }
)(SaveWithNoteButtonView);
Now in React-admin version 3 "Altering the Form Values before Submitting" Can't I do this anymore?
This code does not work:(
import React, { useCallback } from 'react';
import ProcessIcon from '#material-ui/icons/HeadsetMic';
import { useForm, useFormState } from 'react-final-form';
import { SaveButton } from 'react-admin';
const validateProcess = (values) => {
const errors = {};
if (values.files < 1) errors.files = ['resources.Order.errors.files'];
return errors
};
const SaveWithProcessButton = ({ handleSubmitWithRedirect, ...props }) => {
const form = useForm();
const formState = useFormState();
const handleClick = useCallback(() => {
return new Promise((resolve, reject) => {
const errors = validateProcess(formState.values);
if (errors) {
reject(errors)
} else {
form.change('status', "DRAFT");
resolve( handleSubmitWithRedirect('show') );
};
});
}, [form]);
return <SaveButton {...props} handleSubmitWithRedirect={handleClick} label="ra.action.process" icon={<ProcessIcon />} />;
};
export default SaveWithProcessButton;
I manage to do this. Try my code below, I hope it will works for also for you.
const handleClick = useCallback(() => {
if (!formState.valid) {
form.submit();
return;
} else { ... your code goes here }
}, [form]);

Handling Errors from Redux API Call as a Toast

So I'm trying to figure out the best way to display a Toast error and success function when the API call fires from redux.
My line of thinking: Create action for the API call. If successful, then I want the screen to change to the home screen. If it fails, then display the message in a Toast.
Here's what some of my actions look like:
export function getTokenAPI(username, password) {
return async function action(dispatch) {
try {
dispatch({ type: t.AUTH_GET_TOKEN });
dispatch(setLoading(true));
const { data } = await API.authGetToken(username, password);
const { success } = data;
if (success) {
const { access_token, refresh_token } = data;
dispatch(setAccessToken(access_token));
dispatch(setRefreshToken(refresh_token));
await dispatch(setLoading(false));
} else if (!success) {
const { errorMessage } = data;
throw Error(errorMessage);
}
} catch (e) {
dispatch(setError(e.message));
dispatch(setLoading(false));
}
};
}
The setError action sets the error key to true and sets the errorMessage. Here's what my screen looks like:
import React from 'react';
import { Container, View, Toast } from 'native-base';
import styles from './styles';
import { connect } from 'react-redux';
import { authActions } from '_ducks/auth';
const LoginScreen = props => {
const { getToken, navigation } = props;
const { navigate } = navigation;
const navigateToHome = () => navigate('Home');
const handleLogin = async () => {
const { error, errorMessage } = props;
await getToken('sample', 'pass123');
if (error) {
Toast.show({
text: errorMessage,
buttonText: 'kay',
});
} else {
navigateToHome();
}
};
return (
<Container>
<View style={styles.container}>
<LoginButton onPress={handleLogin} />
</View>
</Container>
);
};
const mapDispatchToProps = dispatch => ({
getToken: () => dispatch(authActions.getTokenAPI()),
});
const mapStateToProps = state => ({
isLoading: state.authReducer.isLoading,
error: state.authReducer.error,
errorMessage: state.authReducer.errorMessage,
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LoginScreen);
So if there's an error, then display the toast. If it's successful, navigate to the home screen. Essentially, error will not be true quick enough to make the check within handleLogin work appropriately.
Any recommendations on the pattern or process? Should I be using a useEffect hook here?

How to detect first launch in react-native

What is a good way to detect the first and initial launch of an react-native app, in order to show an on-boarding/introductory screen ?
Your logic should follow this:
class MyStartingComponent extends React.Component {
constructor(){
super();
this.state = {firstLaunch: null};
}
componentDidMount(){
AsyncStorage.getItem("alreadyLaunched").then(value => {
if(value === null){
AsyncStorage.setItem('alreadyLaunched', 'true'); // No need to wait for `setItem` to finish, although you might want to handle errors
this.setState({firstLaunch: true});
}
else{
this.setState({firstLaunch: false});
}}) // Add some error handling, also you can simply do this.setState({fistLaunch: value === null})
}
render(){
if(this.state.firstLaunch === null){
return null; // This is the 'tricky' part: The query to AsyncStorage is not finished, but we have to present something to the user. Null will just render nothing, so you can also put a placeholder of some sort, but effectively the interval between the first mount and AsyncStorage retrieving your data won't be noticeable to the user.
}else if(this.state.firstLaunch === 'true'){
return <FirstLaunchComponent/>
}else{
return <NotFirstLaunchComponent/>
}
}
Hope it helps.
I made some adjustments to martinarroyo's suggestion. AsyncStorage.setItem should set a string value and not a bool.
import { AsyncStorage } from 'react-native';
const HAS_LAUNCHED = 'hasLaunched';
function setAppLaunched() {
AsyncStorage.setItem(HAS_LAUNCHED, 'true');
}
export default async function checkIfFirstLaunch() {
try {
const hasLaunched = await AsyncStorage.getItem(HAS_LAUNCHED);
if (hasLaunched === null) {
setAppLaunched();
return true;
}
return false;
} catch (error) {
return false;
}
}
This function can then be imported wherever you need it. Note that you should render null (or something else clever) while waiting for the async function to check AsyncStorage.
import React from 'react';
import { Text } from 'react-native';
import checkIfFirstLaunch from './utils/checkIfFirstLaunch';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isFirstLaunch: false,
hasCheckedAsyncStorage: false,
};
}
async componentWillMount() {
const isFirstLaunch = await checkIfFirstLaunch();
this.setState({ isFirstLaunch, hasCheckedAsyncStorage: true });
}
render() {
const { hasCheckedAsyncStorage, isFirstLaunch } = this.state;
if (!hasCheckedAsyncStorage) {
return null;
}
return isFirstLaunch ?
<Text>This is the first launch</Text> :
<Text>Has launched before</Text>
;
}
}
In 2022: Note that AsyncStorage from react-native is already deprecated.
Use react-native-async-storage/async-storage instead.
Custom hook:
import React, { useState } from "react";
import AsyncStorage from "#react-native-async-storage/async-storage";
async function checkIfFirstLaunch() {
try {
const hasFirstLaunched = await AsyncStorage.getItem("#usesr_onboarded");
if (hasFirstLaunched === null) {
return true;
}
return false;
} catch (error) {
return false;
}
}
const useGetOnboardingStatus = () => {
const [isFirstLaunch, setIsFirstLaunch] = useState(false);
const [isFirstLaunchIsLoading, setIsFirstLaunchIsLoading] = useState(true);
React.useEffect(async () => {
const firstLaunch = await checkIfFirstLaunch();
setIsFirstLaunch(firstLaunch);
setIsFirstLaunchIsLoading(false);
}, []);
return {
isFirstLaunch: isFirstLaunch,
isLoading: isFirstLaunchIsLoading,
};
};
export default useGetOnboardingStatus;
Usage:
import useGetOnboardingStatus from "../../utils/useGetOnboardingStatus";
const { isFirstLaunch, isLoading: onboardingIsLoading } =
useGetOnboardingStatus();
As Eirik Fosse mentioned: You can use onboardingIsLoading to return null while waiting for the response.