Nuxt3 : Watch doesn't detect response changement with useLazyFetch - vuejs3

I use Nuxt3 and I would like use $fetch
I have a Vue component
<template>
<NuxtLayout>
</NuxtLayout>
</template>
<script setup lang="ts">
import {getQuestions} from "#/server/api/questions";
import {watch} from "vue";
let {data: d, error: e} = getQuestions();
watch(d , n => {
console.log("data", n)
})
watch(e , n => {
console.log("error", n)
})
</script>
My questions module :
import {questions} from "#/api";
export let getQuestions = () => {
const config = useRuntimeConfig()
const { pending, data, error} = useLazyFetch(`${config.public.apiBase}${questions}`);
return {pending, data, error};
}
But all console.log doesn't display anything. Any idea ?
UPDATE
My request works when HMR run, but if i reload my page, request doesn't work. Maybe framework bug ?

Related

Nextjs 13 how to implement dynamic title

I'm having trouble with implementing dynamic title with Next.js 13.
The Documents said, (https://beta.nextjs.org/docs/routing/pages-and-layouts#modifying-head)
Warning: Currently, the <Head> export does not re-render on client-side transition using next/link, only on initial render and reloads. To work around this for <title>, you can use a client component with useEffect that updates document.title. We plan to fix this in a future release.
And then I tried with useEffect to implement dynamic title,
'use client';
import { useEffect } from "react";;
import Head from 'next/head';
interface Props {
params: {slug : string},
searchParams: {id:string}
};
const getPost = async (id: string) => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
const posts = await res.json();
return posts;
};
const Page = ({params, searchParams}: Props) => {
useEffect(() => {
const setDocumentTitle = async () => {
const post = await getPost(params.slug);
document.title = post.title;
}
setDocumentTitle();
}, [params.slug]);
return (<>
<Head>
<title>Blog Post</title>
</Head>
<div>
<h1>Blog Post</h1>
<p>Slug: {params.slug}</p>
<p>Id: {searchParams.id}</p>
</div>
</>);
};
export default Page;
but it is not working. still title is not changed. Is there any way?
You can reproduce it here.codesandbox
The first few times seem to be working well, but the document title does not change if you continue to go back and click Go to Post1 (next/link).

Method "Astronomy/execute" not found in meteor

Okay, I build Game DB schema using astronomy package in meteor.
Then I try to add method to it by extending it in server. (server/gamehandle.js)
import {Game} from '../imports/db/game'
import {DDP} from 'meteor/ddp-client'
Game.extend({
meteorMethods: {
AddNewGame(judul){
const invocation = DDP._CurrentInvocation.get()
this.namaGame = judul
this.creator = invocation.userId
this.createdAt = new Date()
return this.save()
}
}
})
But when I try to run the method in app client using callMethod it throw an error that astronomy/execute not found 404.
This the component using it
import {Game} from '../../../db/game'
export function NewGameList(props){
const { isOpen, onOpen, onClose } = useDisclosure()
const [judul, setJudul] = useState('')
const [hasil, setHasil] = useState(null)
const judulChange = (e) => setJudul(e.target.value)
const AddGame = new Game()
const handleSubmit = (e) => {
e.preventDefault()
AddGame.callMethod('AddNewGame', judul, (err, result) => {
result ? setHasil(result) : setHasil(err.message)
console.log(err)
})
}
...
So enlight me, what thing I do wrong?
Finally found the solution from meteor slack.
Just need to imports my db file to main js file in server.

Using module bundlers and dynamic config firebase

I have an issue where I cannot use init.js, which I have done in the past when importing firebase through the reserved hosting urls.
<script src="/__/firebase/init.js"></script>
This is the script that I am trying to use, and I am importing my firebase modules with:
import * as firebase from "firebase/app";
But I am trying to use webpack, with this. I have tried including init.js in my html, and my bundle as well, but without success.
Is there any way to use init.js with my module bundler?
Pretty late to the party, but better late than never if somebody needs it :)
We wanted to do the same at my company, for two reasons
not having to specify the firebase config ourself, as the init.js script contains it
automatic pickup of emulators when the useEmulator=true query param is specified (handy when you want to choose which emulators to start)
So we trick the script into doing what we want!
Basically the script looks for a global firebase variable which does not exist when using the modules. So we provide one for it to work.
Here's the code we use:
import { initializeApp } from 'firebase/app';
import { connectAuthEmulator, getAuth } from 'firebase/auth';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
import { connectFunctionsEmulator, getFunctions } from 'firebase/functions';
export async function initFirebase(): Promise<void> {
// provide a fake firebase proxy object to the hosting init script
// to get the boilerplate done (firebase conf + automatic connection
// to started emulators)
const proxy: any = {
initializeApp: (c: any) => initializeApp(c),
};
// emulators done under development check to help with the tree-shaking
if (process.env.NODE_ENV === 'development') {
proxy.firestore = () => ({
useEmulator: (h: any, p: any) =>
connectFirestoreEmulator(getFirestore(), h, p),
});
proxy.functions = () => ({
useEmulator: (h: any, p: any) =>
connectFunctionsEmulator(getFunctions(), h, p),
});
proxy.auth = () => ({
useEmulator: (h: any, p: any) => connectAuthEmulator(getAuth(), h, p),
});
}
const _global = globalThis as any;
_global.firebase = proxy;
try {
await import(`/__/firebase/init.js${
process.env.NODE_ENV === 'development' ? '?useEmulator=true' : ''
}`
);
} finally {
delete _global.firebase;
}
}
You'll notice I only setup the proxies for firestore/functions/auth as those are the only ones we emulate at the moment. If you don't care for the emulators, you can skip the entire code paths when process.env.NODE is 'development'.

firebase and gatsby build don't work well together

I get the following error when I try to login:
u.a.auth is not a function
The error is on this line in Login.js:
app.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
At the top, I have import app from "./base.js";
In base.js, I have
import firebase from 'firebase/app';
var config = {
....
};
var app;
if(firebase.apps && firebase.apps.length > 0) {
app = firebase.apps[0];
} else {
app = firebase.initializeApp(config);
}
export default app;
That's after I run
gatsby build
gatsby serve
Hello here's how I did it. It worked fine:
import React from "react";
import firebase from "firebase";
...
const LoginForm = () => {
const login = values => {
firebase
.auth()
.signInWithEmailAndPassword(values.email, values.password)
.then(() => { firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
navigate("/app/profile");
})
.catch(error => {
console.log("do something with the error:", error);
});
}
return(
<form onSubmit={login}>
form details
</form>
);
};
export default LoginForm;

this.$firebase is undefined

I'm building my first Vue.js app, trying to use vuex with vuexfire.
//main.js
import firebase from 'firebase';
...
Vue.prototype.$firebase = firebase.initializeApp(config);
...
firebase.auth().onAuthStateChanged(() => {
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
render: h => h(App),
created() {
this.$store.dispatch('setDealsRef');
},
});
});
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
next('/signin');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
And:
//store/index.js
import Vue from 'vue';
import Vue from 'vue';
import Vuex from 'vuex';
import { firebaseMutations } from 'vuexfire';
...
Vue.use(Vuex);
const db = this.$firebase.firestore();
const dealsRef = db.collection('deals');
And:
//store/mutations.js
export default {
SET_USER(state) {
state.user = this.$firebase.auth().currentUser;
},
...
}
This complies OK, but throws TypeError: this.$firebase is undefined[Learn More] in the console.
Any idea what I'm doing wrong? I think I've read every relevant tutorial and StackOverflow questions, and tried everything.
When you do:
Vue.prototype.$firebase = firebase.initializeApp(config);
You add $firebase to the Vue instance. So for
this.$firebase
to work, the this should be a Vue insteance. In other words, that line must execute inside a Vue method/hook/computed/etc.
And the code you show, doesn't do that:
const db = this.$firebase.firestore();
in the code above, the this is the outer context. (Probably is window.)
So for it to work outside a Vue instance, you have to do:
const db = Vue.prototype.$firebase.firestore();
Provided the line above executes after (in time/order) the line where you initialize the $firebase.
I think I solved the problem:
Moving firebase initialization to store.js
Changing firebase.auth().onAuthStateChanged(() => { to Vue.prototype.firebase.auth().onAuthStateChanged(() => { in main.js
Importing firebase as: import firebase from '#firebase/app';
import '#firebase/firestore';

Resources