Unable to add a Record into Firebase upon creating User in React Native Expo Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Unable to add a Record into Firebase upon creating User in React Native Expo without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I try to create a user in Firebase using the Rest API for Auth, but immediately after I create the user in Auth and get the User UID back I need to do 2 more things:

  1. Upload a Picture to the Firebase Storage.

  2. Create a User Record inside the Collection (Table) of Users in Real-Time Database. Using the Rest API as well. Firebase automated SDK isn’t really working for me.

The First Thing, (Picture upload) I’m able to do it through my code the problem that I’m having is inserting the record to the Collection in the Database.

Here is my sign up Code so far:

export const signup = (email, password, image, nombre) => {
    return async dispatch => {
        const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[my API KEY]', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                email: email,
                password: password,
                returnSecureToken: true,
            })
        });
        if (!response.ok) {
            const errorResData = await response.json();
            const errorId = errorResData.error.message;
            let message = 'Algo salio mal!';
            if (errorId === 'EMAIL_EXISTS') {
                message = 'Este Correo ya esta en Uso';
            }
            throw new Error(message);
        }

        const resData = await response.json();

        const nameImage = resData.localId + '.jpg';
        
        const imageResponse = await fetch(image);
        const blob = await imageResponse.blob();

        var ref = firebase.storage().ref().child("images/"+nameImage);

        await ref.put(blob);

        //la variable url tiene la url de la imagen que se guardara en la tabla usuario
        const url = await ref.getDownloadURL().catch((err) => {console.log(err)});

        writeUser(resData.localId, email, nombre, url); 


        // dispatch(
        //     authenticate(
        //         resData.localId,
        //         resData.idToken,
        //         parseInt(resData.expiresIn) * 1000
        //     )
        // );
        // const expirationDate = new Date(new Date().getTime() + parseInt(resData.expiresIn) * 1000);
        // saveDataToStorage(resData.idToken, resData.localId, expirationDate);
    };
};

Here is the Write User Function:

export const writeUser = async (id, email, nombre, foto) => {
    const responseUser = await fetch(`https://[my Project ID]-default-rtdb.firebaseio.com/users.json/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            name: nombre,
            correo: email,
            image: foto,
            title: 'Albo Aficionado',
            acceso: 0
        })    
    });
    
    console.log(responseUser);
};

When I click to upload or create a user in the Emulator I get an error that doesn’t show in the Terminal:

Error

And when I check my Firebase I find that the Auth User is created:

User Auth

The Image is Uploaded correctly (as it uses the User ID for a name).

user Image

but when looked inside the Real-Time DataBase there is no record matching that UID:

No user in the Data base

And I have tested the End Point with PostMan and it does work at least with Postman.

Finally to keep in mind a few things about my Issue:

  1. I’ve tried both having the Function WriteUser or the content of that function on the Sign Up function, none of those approaches works.

  2. The React Firebase Expo SDK isn’t really working for me.

  3. The DataBase insertion is working through Postman so the Endpoint is working.

  4. It seems as if the code just bypasses that section of code of insertion to the Collection.

Any Ideas of what am I doing wrong and how to fix it?

Kind Regards

Answer

The URL you’re PUTting to is wrong:

fetch(`https://[my Project ID]-default-rtdb.firebaseio.com/users.json/${id}`)

should be

fetch(`https://[my Project ID]-default-rtdb.firebaseio.com/users/${id}.json`)

So with .json at the end of the URL, not in the URL.

We are here to answer your question about Unable to add a Record into Firebase upon creating User in React Native Expo - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji