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!