-2

When I try to upload the image by clicking the button the following error appears:

Untreated promise rejection: TypeError: Unable to read the launchImageLibrary property of null

I've tried importing launchImageLibrary using import * as ImagePicker from 'React-Native-image-Picker', but it didn’t work.

const handleSubmit = async () => {
    const formData = {
        namePet: namePet,
        type: type,
        race: race,
        age: age,
        gender: gender,
        observation: observation,
        imageUrl: imageUrl
    };

    try {
        const response = await axios.post('http://....', formData);
        if (response.status === 201) {
            console.log('Cadastro realizado com sucesso!');
            // Limpar o formulário
            setNamePet('');
            setType('');
            setRace('');
            setAge('');
            setGender('');
            setObservation('');
            setImageUrl('');
        }
    } catch (error) {
        console.error('Erro ao cadastrar:', error);
    }
};

const handleImageUpload = () => {
    const options = {
        mediaType: 'photo',
        quality: 1,
        maxWidth: 500,
        maxHeight: 500,
    };

    launchImageLibrary(options, async response => {
        if (response.didCancel) {
            console.log('Seleção de imagem cancelada');
        } else if (response.error) {
            console.error('Erro ao selecionar imagem:', response.error);
        } else {
            try {
                // Fazer o upload da imagem para o servidor e obter o URL da imagem
                const formData = new FormData();
                formData.append('imageUrl', {
                    uri: response.uri,
                    name: 'image.jpg',
                    type: 'image/jpeg'
                });

                const uploadResponse = await axios.post('Minha URL', formData);
                if (uploadResponse.status === 200) {
                    // Salvar o URL da imagem no estado 'imageUrl'
                    setImageUrl(uploadResponse.data.imageUrl);
                }
            } catch (uploadError) {
                console.error('Erro ao fazer o upload da imagem:', uploadError);
            }
        }
    });
};

return (
    <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding">
        <ScrollView style={styles.container}>
            <View style={{ padding: 20 }}>
                <View style={styles.inputContainer}>
                    <Text>Nome</Text>
                    <TextInput
                        value={namePet}
                        onChangeText={setNamePet}
                        placeholder="Nome do pet"
                    />
                </View>

                <View style={styles.inputContainer}>
                    <Text>Tipo</Text>
                    <TextInput
                        value={type}
                        onChangeText={setType}
                        placeholder="Cão, gato, papagaio..."
                    />
                </View>

                <View style={styles.inputContainer}>
                    <Text>Raça</Text>
                    <TextInput
                        value={race}
                        onChangeText={setRace}
                        placeholder="Raça do pet"
                    />
                </View>

                <View style={styles.inputContainer}>
                    <Text>Idade</Text>
                    <TextInput
                        value={age}
                        onChangeText={setAge}
                        placeholder="Idade do pet"
                    />
                </View>

                <View style={styles.inputContainer}>
                    <Text>Gênero</Text>
                    <TextInput
                        value={gender}
                        onChangeText={setGender}
                        placeholder="Macho ou Fêmea"
                    />
                </View>

                <View style={styles.inputContainerOb}>
                    <Text>Observações</Text>
                    <TextInput
                        value={observation}
                        onChangeText={setObservation}
                        placeholder="Observações sobre o pet"
                        multiline
                    />
                </View>
                <TouchableOpacity
                    style={styles.buttonSubmit}
                    onPress={handleSubmit}                >
                    <Text style={styles.buttonText}>Cadastrar</Text>
                    <Icon name="paw" size={20} color="black" />
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.buttonUpload}
                    onPress={handleImageUpload}
                >
                    <Text style={styles.buttonText}>Enviar Imagem</Text>
                    <Icon name="camera" size={20} color="black" />
                </TouchableOpacity>

            </View>
        </ScrollView>
    </KeyboardAvoidingView>
);

}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    "I need urgent help"—please read [Under what circumstances may I add "urgent" or other similar phrases to my question, in order to obtain faster answers?](https://meta.stackoverflow.com/q/326569/354577) (TL;DR: It's never okay.) – ChrisGPT was on strike Aug 26 '23 at 13:48
  • Somehow this code had "your text" placeholders added when the question was posted. In general this happens when little care is taken in the act of posting. It's fine to make errors when one is new to Stack Overflow, but only up to a point - please always proof-read your work when asking for assistance. – halfer Aug 28 '23 at 21:17

0 Answers0