Error when use Audio.Sound.pauseAsync() in expo-av - react-native

This is my code
const [isPlaying, setIsPlaying] = useState(false);
const [playbackObject, setPlaybackObject] = useState(null as any);
const [playbackStatus, setPlaybackStatus] = useState(null as any);
const handleAudioPlayPause = async () => {
try {
if (playbackObject !== null && playbackStatus === null) {
const status = await playbackObject.loadAsync(
{ uri: audioUri },
{ shouldPlay: true }
);
setIsPlaying(true);
return setPlaybackStatus(status);
}
// // It will pause our audio
if (playbackStatus.isPlaying) {
const status = await playbackObject.pauseAsync();
setIsPlaying(false);
return setPlaybackStatus(status);
}
// It will resume our audio
if (!playbackStatus.isPlaying) {
const status = await playbackObject.playAsync();
setIsPlaying(true);
return setPlaybackStatus(status);
}
} catch (error) {
console.log('error in play/pause ', error);
}
};
the playAsync works fine, and playbackStatus.isPlaying change to true, but when pauseAsync() is executed it throws the following error:
[Error: Encountered an error while setting status!]
I was looking in the documentation and in different forums without a solution yet, I even used the same example and it gives me the same error

Related

null is not an object (evaluating 'LoginManager.logInWithPermissions')

When I try to login to Facebook in expo android app, getting the following error
null is not an object (evaluating 'LoginManager.logInWithPermissions')
const SignInwithFB = async () => {
try {
await LoginManager.logInWithPermissions(["public_profile", "email"]);
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
} catch (e) {
console.log(e);
}
}
installed by following this instructions: https://www.npmjs.com/package/react-native-fbsdk-next
Check Expo installation section in npm install page, make sure you have implemented the instruction
const SignInwithFB = async () => {
try {
const loginManagerResult = await LoginManager.logInWithPermissions(["public_profile", "email"]);
if(loginManagerResult) {
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
}
} catch (e) {
console.log(e);
}
}

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;
}
}

react native image uri and async storage

i'm trying to save a profile picture and i save it with asyncStorage. store part working perfectly but if i close app and reopen it doesn`t show image.
i logging image uri and there is uri but cant solve the problem.
here is my code
this is image pick part
const ImagePick = async () => {
const options = {
title: 'Seçim yapınız.',
cancelButtonTitle: 'İptal',
takePhotoButtonTitle: 'Bir fotoğraf çek',
chooseFromLibraryButtonTitle: 'Galeriden seç',
chooseWhichLibraryTitle: 'Galeriden seç',
mediaType: 'photo',
storageOptions: {skipBackup: true, path: 'images'},
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
ImagePicker.showImagePicker(options, async response => {
//console.log('response', response);
if (response.didCancel) {
console.log('Kullanıcı fotoğraf seçimini iptal etti');
} else if (response.customButton) {
console.log('Özel butona tıklandı.');
} else if (response.error) {
console.log('error', 'Bir hata oluştu.');
} else {
console.log(response.fileName);
let uri = response.uri;
let path = response.uri;
if (Platform.OS === 'ios') {
path = '~' + path.substring(path.indexOf('/Documents'));
}
if (!response.fileName) {
response.fileName = path.split('/').pop();
}
let name = response.fileName;
let type = `image/${name.split('.').slice(-1)[0]}`;
console.log('uri', uri);
console.log('name', name);
console.log('type', type);
setImageUri(response.uri);
try {
await AsyncStorage.setItem('profilePicture', response.uri);
console.log('async storage kayıt başarılı');
} catch (error) {
console.log(error);
}
}
});
}
};
i get image like this
useEffect(() => {
getProfilePicture();
}, []);
const getProfilePicture = async () => {
const profilePicture = await AsyncStorage.getItem('profilePicture');
console.log('profilePicture', profilePicture);
if (profilePicture !== null) {
setImageUri(profilePicture);
setIsLoading(false);
} else {
setImageUri(
'https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg',
);
setIsLoading(false);
}
};
emulator is the problem. in device it's working

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');
}
});

How to use AsyncStorage to store array in 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
}
};