Search code examples
react-nativehashfetchmultipartform-datapatch

getting 422 when calling api with formData from React-Native


The api expects the following:

"user" as a hash (can't even get this to work from postman...) Parameters to be updated as string (name, email and password) Image from "react-native-image-picker" (i have the response from this)

Preparing the upload upload:

    const handleUserUpdate = async () => {
        if (photo === null || photo === undefined) {
            return;
        }

        let avatar = photo.assets[0];
        let uri = avatar.uri?.replace('file://', '');

        // https://stackoverflow.com/questions/32441963/how-to-use-formdata-in-react-native
        let formData = new FormData();
        formData.append('user[avatar]', {
            uri: uri,
            name: avatar.fileName,
            type: avatar.type,
        });
        formData.append('user[name]', 'Foo');

        updateUserAvatar(formData)
            .then(async response => {
                await AsyncAlert('Success', 'Response code: ' + JSON.stringify(response));
            })
            .catch(error => {
                Alert.alert('Error', JSON.stringify(error));
            });
    };

the actual upload:

    updateUserAvatar = async (avatar: FormData) => {
        try {
            await fetch(
                'https://staging.appcms.dk/api/cX8hvUC6GEKGgUuvzsBCNA/app-memberships/',
                {
                    body: JSON.stringify(avatar),
                    method: 'PATCH',
                    credentials: 'include',
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'multipar/form-data',
                    },
                },
            )
                .then(async response => {
                    if (response.ok) {
                        let res = await response.json();
                        console.log(JSON.stringify(res));
                        return res;
                    } else {
                        throw new Error(
                            response.status + ', ' + response.statusText,
                        );
                    }
                })
                .catch(error => {
                    console.log(error);
                    throw error;
                });
        } catch (error) {
            return error;
        }
    };

The only response i get is 422. I don't know how to add user as hash to the formData. Or what is potentially wrong with the header...

Thanks in advance!

I've tried to mimic the Patch call from postman, but i have the same problem as in the code - i don't know how to add a user as hash...


Solution

  • Turns out the documentation for the api call was incomplete, which in turn meant that my header for the request was incomplete...