Search code examples
react-nativeasyncstoragereact-native-image-picker

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

Solution

  • emulator is the problem. in device it's working