Skip to content

Instantly share code, notes, and snippets.

@kiok46
Created June 15, 2017 15:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiok46/421dbc17843212118d78c2fe2cd35c2c to your computer and use it in GitHub Desktop.
Save kiok46/421dbc17843212118d78c2fe2cd35c2c to your computer and use it in GitHub Desktop.
How to setup Async storage and store boolean(true/false) values.

AsyncStorage

Store information in local machine (Mobile).

import { AsyncStorage } from 'react-native';

import {
	AUTOCOMPLETE_SETTING,
	QUACK_ON_REFRESH_SETTING,
} from './types';

// Import action types.

import { INITIAL_STATE } from '../reducers/LoadSettingsReducer';

// Import initial state from the reducer.

export const changeAutocompleteSetting = (autocomplete) => async dispatch => {

	let autocomplete_value = await AsyncStorage.getItem('autocomplete_value');
	autocomplete_value = JSON.parse(autocomplete_value)

	if ( autocomplete_value !== null ) {
		if (autocomplete_value === true) {
			await AsyncStorage.setItem('autocomplete_value', JSON.stringify(false));
			dispatch({
				type: AUTOCOMPLETE_SETTING,
				payload: false
			})
		} else {
			await AsyncStorage.setItem('autocomplete_value', JSON.stringify(true));
			dispatch({
				type: AUTOCOMPLETE_SETTING,
				payload: true
			})
		}
	} else {
		await AsyncStorage.setItem('autocomplete_value', JSON.stringify(INITIAL_STATE.autocomplete));
		dispatch({
			type: AUTOCOMPLETE_SETTING,
			payload: INITIAL_STATE.autocomplete
		})
	}
}

Using the life cycle method to call each action creator and each will dispatch the action and will result in changing the state by reducers.

componentDidMount() {
    // AsyncStorage.clear()
    this.props.changeAutocompleteSetting();
    this.props.changeQuackOnRefreshSetting();
}

but doing so wouldn't solve the problem as componentDidMount is a synchronous method and we know that these methods are take time accessing AsyncStorage. so can what could be the solution?

You can call multiple dispatch statements and this is the beauty of redux-thunk and new aync-await syntax of Javascript.

async componentDidMount() {
    // AsyncStorage.clear()
    await this.props.changeAutocompleteSetting();
    await this.props.changeQuackOnRefreshSetting();
}

cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment