"query is not a function" Next Js getServerSideprops and firebase error - javascript

I'm using NextJS and firebase as my primary database for the app that I'm currently building for an NGO. and I ran into an issue.
import {
collection,
where,
query,
getDocs
} from '#firebase/firestore';
import { db } from '../../../services/firebase';
export async function getServerSideProps({query}) {
const user = await getDocs(query(collection(db, 'members'), where('id', '==', query)))
return {
props: {
// VisionInfo: JSON.stringify(user.docs.map(item => item.data()))
json: JSON.stringify('Hello')
}
};
}
The only way to get Query from the URL in NextJS in serverSideProps is to use the keyword "query" but the same keyword is used to fetch firebase document.
The error shows "query is not a function"
Is there anyway I could get Query into serversideprops ?

The issue arises because you also have "query" in getServerSideProps parameters. Try naming the import from Firestore SDK (or the query param) as shown below:
import { query as fireQuery } from '#firebase/firestore';
export async function getServerSideProps({query}) {
const user = await getDocs(fireQuery(collection(db, 'members'), where('id', '==', query)))
// use fireQuery here ^^^
})

Related

Firebase .data() function is not found

I did manually set up the entire data into Firebase Firestore have been trying to retrieve the data as followed
import app, { db } from "./app";
import {
addDoc,
collection,
doc,
getDocs,
getFirestore,
limit,
orderBy,
query,
setDoc,
Timestamp,
} from "firebase/firestore";
export default async function getEvents() {
const db = getFirestore(app);
const first = collection(db, "Events");
const docSnap = await getDocs(first);
console.log(docSnap.data());
}
The thing over here is that the console throws an error saying that docSnap.data() is not a function
TypeError: docSnap.data is not a function
Yes apparently the mistake I did was that I need to specify the document before I get it's data, So the correct thing to do would be
console.log(docSnap.docs[0].data());
If you want all the data from all the elements maybe you can loop over them or just map them depending over your preference.

firebase__WEBPACK_IMPORTED_MODULE_2___default error react.js

I have this firebase error I am receiving, never seen It before. I had used stripe api / extension in connection with firebase and when i'm go to save the data in firebase db, it gives me the error firebase__WEBPACK_IMPORTED_MODULE_2___default function
Here is my code "db.js" :
import getStripe from "./stripe";
import firestore from "../firebase/index"
export async function createCheckoutSession (uid){
const checkout_sessionsRef =await firestore
.collection('user')
.doc(uid)
.collection('checkout_sessions')
.add({
price : 'price_1IGEdTKDPaWWeL1ymwWH5Ubb',
success_url :window.location.origin,
cancel_url:window.location.origin,
});
checkout_sessionsRef.onSnapshot(async (snap) => {
const {sessionId} =snap.data();
if (sessionId ){
const stripe = await getStripe();
stripe.redirectToCheckout({sessionId})
}
})
}
any ideas on how to fix?

Problems accessing data from a GraphQL query in Javascript with Svelte

Below I have my working function using a normal REST response that I want to try to convert into a GraphQL version, it fetches a JSON doc from my Phoenix Server and stores the object values from the JSON doc into an object. The problem is, here I can use await and then assign the new object values from the object within the JSON document, but using GraphQL I cannot access this data to assign it because there is no await function as its just a Query. (From what I know)
async function updatePageWithNewCompany(company){
const res = await fetch(`http://localhost:4000/${company}`);
profile = await res.json();
profile = profile.companyProfile
DashboardStore.update(currentData => {
return {
id: profile.id,
companyName: `${profile.company_name}`,
averageLength: profile.average_length,
}
})
Ultimately I am asking if there is a way to access and assign data from a GraphQL query in JavaScript so I can manipulate it before displaying it in my frontend Svelte app.
Example of current GraphQL query:
import { gql } from '#apollo/client'
import { client } from './apollo';
import { query, setClient } from "svelte-apollo";
setClient(client)
const GET_COMPANY = gql`
query{
companyProfile(){
companyName
averageLength
}
}
`;
const response = query(GET_COMPANY)
...
svelte-apollo queries return
a svelte store of promises that resolve as values come in
as stated in the example query displayed in the documentation.
As such, you can exploit that format directly in the script section. Here is an example:
...
async function getCompany() {
const companyStore = query(GET_COMPANY)
const company = (await $companyStore).data.companyProfile
return company // format will be an object with keys { companyName, averageLength } according to your query
}
...
On a side-note I would recommend always getting the id of objects in your GraphQL queries as it is usually the key used internally by the Apollo client to manage its cache (unless explicitly stated otherwise).
I have found a working solution with the help of #Thomas-Hennes
import { client } from '../apollo.js';
import { onMount } from "svelte";
import { gql } from '#apollo/client'
export const COMPANY_LIST = gql`
query {
listCompanies{
companyName
}
}
`;
async function listCompanies() {
await client.query({query: COMPANY_LIST})
.then(res => {
companyList.update( currentData =>
[...res.data.listCompanies.companyName])})
};
onMount(() =>{
listCompanies()
})
await didn't like being assigned to a variable or having its data manipulated so i used it as a promise instead and manipulated the response.
The below link helped me find the final piece of the puzzle.
https://docs.realm.io/sync/graphql-web-access/using-the-graphql-client

Firestore Function DocumentReference.update() called with invalid data. Unsupported field value: a custom object

I'm following Firebase's instructions and my functions is as follows:
import { DataSource, DataSourceConfig } from "apollo-datasource";
import { KeyValueCache } from "apollo-server-caching";
import firebase from "firebase";
import admin from "firebase-admin";
import "#firebase/firestore";
import { Request } from "apollo-server-env";
export class FirebaseDataSource<TContext = any> extends DataSource {
context!: TContext;
db: firebase.firestore.Firestore;
constructor({
firebaseConfig,
serviceAccount,
databaseURL,
}: {
serviceAccount: any;
firebaseConfig: firebase.app.App;
databaseURL: string;
}) {
super();
this.context;
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL,
});
}
if (!this.db) {
this.db = firebase.firestore();
}
}
async initialize(config: DataSourceConfig<TContext & { request: Request }>) {
this.context = config.context;
}
async user_updateRestaurantFavorites(data: {
uid: string;
someId: string;
add: boolean;
}) {
const collectionRef = this.db.collection("users");
const documentRef = collectionRef.doc(data.uid);
let favorites;
if (data.add) {
favorites = await documentRef.update({
favorites: admin.firestore.FieldValue.arrayUnion(
data.someId
),
});
} else {
favorites = await documentRef.update({
favorites: admin.firestore.FieldValue.arrayRemove(
data.someId
),
});
}
return favorites;
}
}
export default FirebaseDataSource;
I dubugged it and I do pass the uid, add, and someId correctly.
someId is a string and add is a boolean (true)
When I run this, I get:
Firestore Function DocumentReference.update() called with invalid data. Unsupported field value: a custom object (found in field favorites in document users/XXXXXXX)
I am just running their own function with a simple string.
Below is an image of my firestore showing the user record does indeed have an empty array ready to accept strings
What am I doing wrong?
You're mixing up the web client and admin client SDKs. You can't use the FieldValue objects exported by firebase-admin when calling methods exported by firebase. The error message is coming from the web client SDK, and it's effectively telling you that you passed an object that it doesn't understand (from the Admin SDK).
You should pick one or the other, and completely remove the one you aren't using in order to avoid problems. If this runs on a backend, you should only use the Firebase Admin SDK, and skip the web client altogether. If you do this, you will need to assign this.db using the admin SDK, probably as this.db = admin.firestore().
Firebase can only store primitive types, maps and array of same. In your case you are saving the result of admin.firestore.FieldValue.arrayUnion(...) for the property favorites.
My guess is that the result is not returning a supported type. I have not used FieldValue before ... is that the correct way to use the API?
It simply means that you need to send exact data which was received by the query. Partial object not allowed
db.collection("users").where("name", "==", somename).limit(1).get().then(query => {
console.log(query);
const thing = query.docs[0];
console.log(thing.data());
let tmp = thing.data();
tmp.current_game_play = tmp.current_game_play + 1;
console.log(tmp);
thing.ref.update(tmp);
});

How to make requests to GraphQL-server from my redux action?

I have react+redux application and I want to replace rest-requests in my actions to grapqhl-requests. What is the most simple method to do it?
I read about apollo, but I just to want add graphql in my existing requests.
You must change the way you will get the data because Apollo is a layer between you and the Api requested where you can join many Apis into one single query call.
The example above is very simple and just to explain the way will place your querys and how it connects to Apollo Server. You can set middlewares to log requests on add some headers too.
You will install [https://github.com/apollographql/react-apollo] and [https://github.com/apollographql/graphql-tag]
After that create a connection file in your project that imports
graphClient.js
import { ApolloClient, createNetworkInterface } from 'react-apollo';
const networkInterface = createNetworkInterface({
uri: 'yourserver address'
});
const client = new ApolloClient({
networkInterface,
});
export default client;
yourRequestFile.js
import gql from 'graphql-tag';
import client from './graphClient';
export const getYourData = () => ({
query: gql`
query {
products() {
info {
value {
qty
value
}
}
}
}`,
});
const returnYourData = async () => client.query(getYourdata());
export default returnYourData;

Categories

Resources