Home > Back-end >  Trying make a edit user with react-native, but i can't send edit information to api. json.erro:
Trying make a edit user with react-native, but i can't send edit information to api. json.erro:

Time:03-15

Here I am creating the const to receive the states below. But I need to put them all in just one object to pass to api.

    const [name, changeName] = useState('');
    const [email, changeEmail] = useState('');
    const [password, changePassword] = useState('');
    const [password_confirm, changeConfirm] = useState('');

This is the click function that will wait for the user to enter all the fields and click. So it triggers the function and checks if the fields are not empty and sends the object(body) to api.

    const handleSignClick = async () => {
        if(name != '' && email != '' && password != '' && password_confirm != '') {
            const body = [name, email, password, password_confirm];
            let json = await Api.updateUser(body);

                \*Received*/
             console.log(body);

            if(json.token) {
                await AsyncStorage.setItem('token', json.token);

                userDispatch({
                    type: 'setAvatar',
                    payload:{
                        avatar: json.data.avatar
                    }
                });

                navigation.reset({
                    routes:[{name:'MainTab'}]
                });

            } else {
                alert("Erro: " json.error);
            }
        } else {
            alert("Preencha os campos");
        }
    }

API

    updateUser: async (body) => {
            const req = await fetch(`${BASE_API}/user`, {
                method: 'PUT',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(body)
            });
            const json = await req.json();    
            return json;
    },

CodePudding user response:

Fetch's API Request body should object instead array.

const body = {name, email, password, password_confirm};
  • Related