Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 15 hours ago.
Improve this question
I am getting an Error when using database _query
Error
ERROR TypeError: _query is not a function. (In '_query((0, _database.ref)(_FirebaseConfig.database, 'users'), (0, _database.orderByChild)('email'), (0, _database.equalTo)(email))', '_query' is undefined)
code:
(note that query is not being highlighted as used )
import { ref, get, set, orderByChild, equalTo, query } from 'firebase/database';
useEffect(() => {
const writeToDatabase = () => {
const email = UserDataFromGoogleAuth.email;
if (email) {
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(query)
.then((snapshot) => {
const uuid = snapshot.exists() ? Object.keys(snapshot.val())[0] : uid();
const userRef = ref(database, `/users/${uuid}`);
const userData = {
id: uuid,
name: UserDataFromGoogleAuth.displayName,
email: email,
profilePicture: UserDataFromGoogleAuth.photoURL,
};
return set(userRef, userData);
})
}
};
writeToDatabase();
}, [location, UserDataFromGoogleAuth, props.online, database]);
**
"firebase": "^9.17.1",**
I am getting an Error when using database _query
On this line:
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
You define a variable called query and then try to assign it a value based on calling that same uninitialized variable because it shadow's the query method you are importing from the firebase/database library.
Rename the variable to something else to prevent shadowing the imported method.
const usersWithMatchingEmailQuery = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(usersWithMatchingEmailQuery)
.then(/* ... */)
Note: Don't forget to add a catch() to that Promise chain to handle errors.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
import axios from "axios";
import React, {useState, useEffect} from "react";
export default function Dashboard({token}) {
const [playlist_id, setPlaylistId] = useState([]);
const [href, setHref] = useState([]);
const [playlists, setPlaylists] = useState([]);
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
const getTracks = async (token) =>{
const {tracks} = await axios.get("https://api.spotify.com/v1/playlists/4FteCV6SQS8yKc6pzFlZnv/tracks", {
headers: {
Authorization: 'Bearer '+token
},
params: {
market: "US",
limit: 50,
offset: 0
}
})
console.log({tracks})
}
setIsMounted(true);
//getPlaylists(token);
getTracks(token);
}, [])
if(isMounted)
return(
<div className="Dashboard">
<h1>Hello</h1>
</div>
)};
I am trying to get the items in a public spotify playlist through axios, but the request retrieves an undefined object every time. Should I be using a different token with a special scope? Is there something I am missing with my API call?
These are the strings I am using to retrieve the original token:
const CLIENT_ID = "00c7cd96ee6940879762750970dc5863"
const REDIRECT_URI = "http://localhost:3000"
const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
const RESPONSE_TYPE = "token"
I was able to make a similar call to retrieve all the playlists of a user and the response was const {data}
axios.get returns a Response object. That object doesn't have tracks property.
You probably wanted to do:
const {data: tracks} = axios.get(/* url */)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I don't have a code to share. I am using a template that's built using react + Redux.
The issue I ran into is that if I want multiple users to use the app, the state gets shared with everyone. It makes no difference between users. So the problem I have is one use will see the state of another user who just logged in before. Another one is I am fetching data to display in a chart and somehow the numbers are incrementing everytime it fetches and gets worse if multiple users are logged in.
My question is... How do you manage a react app with multiple users along with Redux? It seems most tutorial I found somehow assume there is only one user.
Most easiest solution is, if your APP is using database that fetched from an API, everytime you start your request, you should clear the data first
here's my reducer example (I'm using redux-tools)
reducers: {
getRoleDetailStart(state) {
state[CURRENT_NAMESPACE].data = {};
state[CURRENT_NAMESPACE].isLoading = true;
state[CURRENT_NAMESPACE].error = null;
},
getRoleDetailSuccess(state, action) {
const { data } = action.payload;
state[CURRENT_NAMESPACE].data = data;
state[CURRENT_NAMESPACE].isLoading = false;
state[CURRENT_NAMESPACE].error = null;
},
getRoleDetailError(state, action) {
state.isLoading = false;
state.error = action.payload;
},
},
actions
export const fetchRootGetRoleDetail = ({ roleId }) => async (
dispatch,
getState
) => {
const state = getState();
const selectedState = state[PARENT_NAMESPACE][CURRENT_NAMESPACE];
const { isLoading } = selectedState;
if (isLoading) return;
try {
dispatch(getRoleDetailStart());
const data = await restRootGetRoleDetail({
roleId,
});
dispatch(
getRoleDetailSuccess({
data,
})
);
} catch (err) {
if (isValidJSON(err)) {
return dispatch(getRoleDetailError(JSON.parse(err).message));
}
dispatch(getRoleDetailError(err));
}
};
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Can anyone explain what is the problem here?
I'm not even using TS this is just javascript
async addChat(message) {
const now = new Date()
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
}
const response = await this.chats.add(chat)
return response
}
I'm sorry, dumb mistake, this was outside of my class
class Chatroom {
constructor(room, username) {
this.room = room
this.username = username
this.chats = db.collection('chats')
}
async addChat(message) {
const now = new Date()
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
}
const response = await this.chats.add(chat)
return response
}
}
The issue is with your function declaration. You need to either do this
async function addChat() {
....
}
or
addChat = async () => {
....
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So I am trying to work with notifications from device to device and this error is driving me crazy, I don't know where I am doing wrong. I have tried everything and searched up to my best to solve this, any help is greatly appreciated. Thank you!
[EDIT : i had posted the question about another error here and it got solved but lead to this new error]
This is my FirebaseMessagingClass
package com.pappu5.navigation;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseMessaging extends
com.google.firebase.messaging.FirebaseMessagingService {
private String channelId = "com.pappu5.navigation";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notificationTtile = remoteMessage.getNotification().getTitle();
String notificationBody = remoteMessage.getNotification().getBody();
String clickAction = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notificationTtile)
.setContentText(notificationBody)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
int notificationId = (int) System.currentTimeMillis();
Intent intent = new Intent(clickAction);
intent.putExtra("user_id",from_user_id);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());
}
This is Firebase index.js file
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{user_id}/{notification_id}').
onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to : ',
context.params.user_id);
const fromUser =
admin.database().ref('/Notifications/'+user_id+'/'+notification_id +
'/From').once('value');
return fromUser.then(fromUserResult => {
const from_user = fromUserResult.val();
console.log('You have new notification from : ',from_user);
const use_Query =
admin.database().ref(`/Chat_Profiles/{from_user}/name`).once('value');
const deviceToken =
admin.database().ref(`/Chat_Profiles/{user_id}/device_token`)
.once('value');
return Promise.all([use_Query,deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title: "Friend Request",
body: userName+" has sent you request",
icon: "default",
click_action : "com.pappu5.navigation_TARGET_NOTIFICATION"
},
data : {
from_user_id: from_user
}
};
console.log(payload);
return admin.messaging().sendToDevice(token_id,payload).then(response => {
return console.log('This was the notification feature');
});
});
});
});
In 'Chat_Profiles/'+from_user+'/name', from_user is an object. The default toString of an object returns [object Object], which is why you get "/Chat_Profiles/[object Object]/name", which is being refused. You likely wanted to use user_id, and not from_user.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Getting a parsing error in javascript while deploying firebase functions... Its showing unexpected token which if i'm not mistaken means that there is an unexpected character somewhere... Stuck here for weeks now... Can somone help me out please
Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref(`/Notifications/${user_id}/${notification_id}/`).onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to ', user_id);
if (!change.after.val()) {
return console.log("A Notification has been deleted from the database", notification_id);
}
const fromUser = admin.database().ref('/Notifications/${user_id}/${notification_id}').once('value');
return fromUser.then(fromUserResult => {
const fromUserId = fromUserResult.val().from;
console.log('You have a new notification from : ', from_user_id);
const userQuery = admin.database().ref('UserData/${fromUserId}/name').once('value');
return userQuery.then(userResult => {
const userName = userResult.val();
const deviceToken = admin.database().ref(`/UserData/${user_id}/TokenID`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: '${userName}',
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notofication Feature');
});
});
});
});
You're missing two pairs of }) at the end of the file. So:
...
return admin.messaging().sendToDevice(token_id, payload).then(response =>{
return console.log('This was the notofication Feature');
});
});
});
});
});
It is understandably impossible to see this with your current code.
The lack of indentation makes it incredibly hard to parse. That's why I passed the code through http://jsbeautifier.org/, which makes it much easier to parse.
I also recommend using a tool like https://eslint.org/demo/ to make it easier to find mistakes like this.
you'll still have few bugs in your code. on three places you're using single quote ' instead of back-tick `
...
const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
...
const userQuery = admin.database().ref(`UserData/${fromUserId}/name`).once('value');
...
const payload = {
notification: {
title: `${userName}`,
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};