Using RTK Query to store data in a Firebase Realtime Database

Currently, I am facing an issue while trying to retrieve data from a Firebase Realtime Database using RTK Query. The code in this section is throwing an error because the return value is incorrect. If anyone has experience with this particular issue, I would greatly appreciate it if you could assist me in correcting the code.

import { createApi, fakeBaseQuery } from "@reduxjs/toolkit/query/react";
import { onValue, ref } from "firebase/database";
import { db } from "libs/firebase";

export const userApi = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: builder => ({
    getUser: builder.query({
      queryFn(uid) {
        try {
          onValue(ref(db, `users/user${uid}`), snapshot => {
            return { data: snapshot.val() };
          });
        } catch (e) {
          return { error: e };
        }
      },
    }),
  }),
});

export const { useGetUserQuery } = userApi;

import { configureStore } from "@reduxjs/toolkit";
import { userApi } from "./apiSlice";

export const store = configureStore({
  reducer: {
    [userApi.reducerPath]: userApi.reducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(userApi.middleware),
});
const { data: user, error, isLoading, isSuccess } = useGetUserQuery(1);
console.log(user);

error message

Answer №1

Consider using a code snippet like the one below:

export const userApi = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: (builder) => ({
    getUser: builder.query({
      async queryFn(uid) {
        try {
          const data = await new Promise((resolve, reject) =>
            onValue(
              ref(db, `users/user${uid}`),
              (snapshot) => resolve(snapshot.toJSON()),
              reject
            )
          );
          return { data };
        } catch (e) {
          return { error: e };
        }
      },
    }),
  }),
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing PHP to dynamically generate href links based on radio button selection in real-time interaction with JavaScript

Currently, I am utilizing the MVC framework within Codeigniter and I have a view that contains a link. It's important to mention that the href value is generated by calling a PHP function which takes 'auth/mylogin' as a parameter: <a hre ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

A function that handles HTTP request and response

In order to decrypt data, I need to retrieve the encrypted response by hitting a specific URL and then use that encrypted data along with a key to decrypt it. Initially, I attempted to fetch the data response using POSTMAN, but all I got back was a series ...

Fire the click event following the parsing of the HTML page

Is it possible to programmatically navigate to a URL, retrieve the response, and then activate the JavaScript click event of an HTML element within that response? For example, if the response contains an element like this: <div id="test">Click me< ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

Converting city/country combinations to timezones using Node.js: A comprehensive guide

When provided with the name of a city and country, what is the most reliable method for determining its timezone? ...

Is it possible to set the radius of a d3.js circle using a style attribute?

Learn more about styling in d3.js with this detailed guide that explains how style attributes can be leveraged to customize the look of a circle, including fill color, stroke color, and stroke width. Is it possible to adjust the radius of a d3.js circle u ...

"The combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

Modify the parameters of the apps.facebook.com URL using the Facebook API

Is there a way to modify the parameters in the URL for apps.facebook.com using JavaScript? For instance, if a user chooses a photo, can we change the URL to apps.facebook.com/myapp/?photo_id=23234? This would allow the user to easily share the link with a ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

How can I define a schema attribute for a controller in Express JavaScript?

Hello, I am brand new to exploring stack overflow and the world of development. I have been self-teaching myself how to code using React and Express, so please forgive me if my question seems basic or implausible. I still have many fundamental gaps in my k ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...

Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality w ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Set a value for the hidden field on the page using client-side scripting

When working with an ASP.net application, I often use Page.ClientScript.RegisterHiddenField("hf_Name", value). However, I am curious about how to override or set a new value for the same Hidden Field 'hf_Name' in the code behind. Can you provide ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

Retrieving QueryString from Request or JavaScript

On my aspx page, I am dealing with a query string - www.mysite.com/enter.aspx?dest=#. After clicking "enter," the page navigates to main.aspx. I am looking for a way to extract this "?dest=#" from the query string in main.aspx using either request.querystr ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...