I dont want to use textfield to insert name, rather than to upload it automatically in the firebase storage along with the form!!
onPressed: () {
final snackBar = SnackBar(
content: const Text('Successfully Uploaded!!!'),
action: SnackBarAction(onPressed: () {}, label: 'Undo',),
);
final post = Post(
location: locationController.text,
type: typeController.text,
facilities: facilitiesController.text,
price: int.parse(priceController.text),
contact: int.parse(contactController.text),
date_time: FieldValue.serverTimestamp(),
// name: nameController.text,
name: User.getDisplayName(),
);
}
you can not upload your text to firebase storage because it only saves only files like images and documents, but it can be saved to firebase-realtime database or firestore, you can store you name to firestore by using this
final snackBar = SnackBar(
content: const Text('Successfully Uploaded!!!'),
action: SnackBarAction(onPressed: () {}, label: 'Undo',),
);
final post = Post(
location: locationController.text,
type: typeController.text,
facilities: facilitiesController.text,
price: int.parse(priceController.text),
contact: int.parse(contactController.text),
date_time: FieldValue.serverTimestamp(),
// name: nameController.text,
name: User.getDisplayName(),
);
FirebaseFirestore.instance.collection("userName").add(
name: //yourname
;
);
Related
I have a question about axios POST and GET requests.
I am working on a Next.js project to build an online store and I am using headless wordpress. The store-system I am using is called WooCommerce.
On the first page I make a POST request, which adds an order to my WooCommerce API. Basically, my POST request just adds an entry to the JSON-object.
On the next page I try to retrieve ALL my orders, but unfortunately the order that was just placed is not (always) on the list… Sometimes after reloading, it updated to the correct one. When I check at the API, all my orders are listed. I have already spend two weeks figuring out what I am doing wrong. I would be very grateful, if somebody could help me with this one.
Thank you very much in advance.
so here I have the relevant code at the checkout page (first page):
const buyNowButton = async (e) => {
...
const variation_id = JSON.parse(sessionStorage.getItem('dwgOrpdf'));
// console.log('variation_id', variation_id[0].variationID);
const line_items = valuesServer.map((item) => {
return {
product_id: item.feature.properties.main_id,
variation_id: variation_id[0].variationID, //item.feature.properties.dwg_id, austasch mit pdf oder dwg id
quantity: 1,
total: '0.00',
};
});
// console.log('lineItems', line_items);
let orderData = {
payment_method: 'bacs',
payment_method_title: 'Direct Bank Transfer',
set_paid: true,
billing: {
first_name: 'John',
last_name: 'Doe',
company: 'example',
address_1: 'example',
address_2: 'example',
city: 'example',
state: 'example',
postcode: '123456',
country: 'example',
email: membemail,
phone: '12345678',
},
shipping: {
first_name: 'John',
last_name: 'Doe',
company: 'example',
address_1: 'example',
address_2: 'example',
city: 'example',
state: 'example',
postcode: '123456',
country: 'example',
phone: '12345678',
},
// these are the products sent to the order
line_items: line_items,
shipping_lines: [
{
method_id: 'flat_rate',
method_title: 'Flat Rate',
total: '0.00',
},
],
};
axios
.post(
`webpageurl/wp-json/wc/v3/orders?consumer_key=${wcConsumerKey}&consumer_secret=${wcConsumerSecret}`,
orderData
.then((response) => {
setMembEmail('');
return response;
})
.catch((err) => {
// console.log('AXIOS ERROR processOrder: ', err);
// setOrderError(err);
});
};
And then on the next page I'll send some GET-requests to receive the data:
export default function Home({
headermenusp,
titlesp,
faviconsp,
logoimagesp,
footermenu,
page,
PageUpdate,
lastOrderLineItems,
}) {...};
return(
<>
...
</>
);
export async function getServerSideProps({ req, res }) {
const cookies = new Cookies(req, res);
let latestEmail = cookies.get('email');
...
const { data: orderID } = await axios.get(
`webpageurl/wp-json/wc/v3/orders/?search=${latestEmail}&consumer_key=${wcConsumerKey}&
consumer_secret=${wcConsumerSecret}`
);
const orderIds = orderID.map((item) => item.id);
console.log('orderIds', orderIds);
...
return {
props: { //I return a bunch of other props here...
page,
headermenusp,
footermenu,
titlesp,
postssp,
logoimagesp,
PageUpdate,
lastOrderLineItems,
},
};
}
Now this last console.log only returns all orders exept the last one.
If I refresh the page, it loads all!
I am using Pinia to fetch and store blog comments from Firebase Firestore.
I can not figure out why the comments array is undefined when fetching from Firestore when using the server route api in Nuxt 3 (see below code).
Yet, I do see data coming in when console logging the fetch request from Pinia
/stores/comments.ts:
import {defineStore} from 'pinia'
export const useComment = defineStore('comment', {
state: () => {
return {
comments: []
}
},
actions: {
async fetchComments(routeParamsId: String) {
console.log(1, routeParamsId)
const {data} = await useFetch(`/api/comments/${routeParamsId}`)
console.log(2, data)
this.comments = data
}
}
})
The comments.vue component:
<script setup>
import { useComment } from '#/stores/comment'
const route = useRoute()
const commentStore = useComment()
const comments = await commentStore.fetchComments(route.params.id)
console.log(3, comments) // <---- console log says: 3, undefined
</script>
Console.log 3 shows: 3, undefined
1 sdfgsdfgsdfg_wsCb
2 RefImpl {
__v_isShallow: false,
dep: undefined,
__v_isRef: true,
_rawValue: [
{
comment: 'test comment',
displayName: 'John Doe',
likes: 0,
uid: 'TIkHA7B3akn28biaGU5sJ0riZp2',
createdAt: [Object],
postId: 'sdfgsdfgsdfg_wsCb',
commentId: 'mHRoyGlfJrZNSnPBEo7m',
parentCommentId: null
}
],
_value: [
{
comment: 'test comment',
displayName: 'John Doe,
likes: 0,
uid: 'TIkHA7B3akn28biaGU5sJ0riZp2',
createdAt: [Object],
postId: 'sdfgsdfgsdfg_wsCb',
commentId: 'mHRoyGlfJrZNSnPBEo7m',
parentCommentId: null
}
]
}
server/api/comments/[postId].ts:
import { firestore } from '#/server/utils/firebase'
export default defineEventHandler(async (event) => {
// console.log(2, event.context.params.postId)
const commentsRef = firestore.collection('comments')
const snapshot = await commentsRef.where('postId', '==', event.context.params.postId).get()
const comments = []
if (snapshot.empty) {
console.log('No matching documents.')
return
}
snapshot.forEach(doc => {
comments.push(doc.data())
})
return comments
})
Should I be setting up the fetch differently somewhere in comments.vue file?
So a couple of issues here that I have fixed which solves my question:
First, it's recommended to use $fetch method when fetching data in Pinia store:
https://github.com/nuxt/framework/discussions/2940#discussioncomment-2052627
(it also works better when troubleshooting Pinia data fetching within Vue Devtools)
Second, the mistake I made was that I was doing:
const comments = await commentStore.fetchComments(route.params.id)
and I needed to call the comments array from the store directly, rather than using the action. Thus, I had updated my Comments.vue code like so:
<template>
<AppSpinner v-if="loading" />
<CommentsList :comments="commentStore.comments" v-else />
</template>
<script setup>
import { useComment } from '#/stores/comment'
const route = useRoute()
const commentStore = useComment()
const loading = ref(false)
loading.value = true
await commentStore.fetchComments(route.params.id)
loading.value = false
</script>
I have a simple function that register users in firebase and save data in cloud firestore
But I am getting this error:
[TypeError: Cannot call a class as a function]
Can anyone help my find where is located the error?
function below:
const handleSignUp = useCallback(
async data => {
try {
setLoading(true);
const auth = await authFB().createUserWithEmailAndPassword(
data.email,
data.password,
);
const db = firestore();
const firstName = data.name.split(' ').slice(0, -1).join(' ');
const lastName = data.name.split(' ').slice(-1).join(' ');
await db
.collection('Providers')
.doc(auth.user.uid)
.set({
id: auth.user.uid,
name: {
first: firstName,
last: lastName,
},
email: data.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
address: {
position: firestore.GeoPoint(
coordinates.latitude,
coordinates.longitude,
),
},
})
.then(() => {
navigation.reset({
routes: [{ name: 'SignIn' }],
index: 0,
});
});
setLoading(false);
Alert.alert(
'Cadastro realizado com sucesso!',
'Você já pode fazer login na aplicação.',
);
} catch (err) {
setLoading(false);
}
},
[coordinates],
);
I'm not terribly familiar with the Firestore API, but most likely you just need the new keyword where you're creating a GeoPoint:
position: new firestore.GeoPoint(
coordinates.latitude,
coordinates.longitude,
),
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-games')
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
const gameSchema = new mongoose.Schema({
title: String,
publisher: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
onSale: Boolean,
price: Number
});
const Game = mongoose.model('Game', gameSchema);
async function saveGame() {
const game = new Game({
title: "The Legend of Zelda: Breath of the Wild",
publisher: "Nintendo",
tags: ["adventure", "action"],
onSale: false,
price: 59.99,
});
const result = await game.save();
console.log(result);
}
saveGame();
My doubt about the code is that : how in this code async/await function is used. What is use of that. Can we not make this without using them.
SOurce : https://vegibit.com/mongoose-crud-tutorial/
On a List module, I created a bulk action button to generate PDF by calling a custom action.
The problem is <Datagrid> checkboxes are not unselected once the action is executed.
Here is my custom action:
export const print = (resource, ids, data) => ({
type: DOWNLOAD,
payload: {
id: ids.length === 1 ? ids[0] : ids,
data,
},
meta: {
resource: resource,
fetch: PRINT,
onFailure: {
notification: {
body: 'ra.notification.http_error',
level: 'warning',
},
},
},
});
And here is my button:
class PrintBulkButton extends React.Component {
handleClick = () => {
const { basePath, options, print, resource, selectedIds } = this.props;
print(resource, selectedIds, options, basePath);
};
render() {
return (
<Button {...sanitizeRestProps(this.props)} onClick={this.handleClick}>
{this.props.icon}
</Button>
);
}
}
I'm using react-admin 2.3.0, but it wasn't working with previous versions either.
I think the checkboxes are not unchecked because the service I call doesn't update data.
Am I right?
Do I have to call another service or action to uncheck them, or am I missing something?
You can add this onSuccess side effect parameter unselectAll: true that we should document (please open an issue for it):
export const print = (resource, ids, data) => ({
type: DOWNLOAD,
payload: {
id: ids.length === 1 ? ids[0] : ids,
data,
},
meta: {
resource: resource,
fetch: PRINT,
onSuccess: {
unselectAll: true,
},
onFailure: {
notification: {
body: 'ra.notification.http_error',
level: 'warning',
},
},
},
});