What is the difference between axios and useFetch (nuxt 3)? - nuxtjs3

I'm slowly starting to migrate from nuxt 2 to nuxt 3.
Previously I used to use axios.
In Nuxt3, it is recommended to use useFetch
However the behavior is quite weird with useFetch. Calls are not made systematically.
For example in this piece of code :
async mounted() {
const store = useAuth();
let response = await axios.get('http://dev.test.fr/api/secured/admin', {headers : store.authHeader() });
this.sensibleInformation = response.data;
},
With Axios, every time I open this page, the call is made and the sensibleInformation is up to date.
With useFetch, the syntax is similar
async mounted() {
const store = useAuth();
let response = await useFetch('http://dev.malt.fr/api/secured/admin' , {method : 'get', headers : store.authHeader() });
this.sensibleInformation = response.data;
},
But the call to the server is done... sometimes. So, the sensibleInformation is most of the time empty. And I don't find any explanation in the documentation.
Maybe there is something I miss here.
I'm using nuxt 3.0.0-rc.6

As it is explained in nuxtJS3 useFetch
useFetch is a wrapper for $fetch(come from here ohmyfetch)
you don't need to import this lib it is include in vuejs3 and lastly axios was not compatible with vuejs3 explained here why use $fetch
what is really great is that body is automatically parsed in JSON, so no need to parse or stringify anything. Also header for content type is automatically added.
So no need to import any library, automatic parsing, automatic header detected etc...

Not sure about this one, but I think the "useFetch" helper is designed to be used with the Vue composition API, so :
within the "setup" function
directly in your script tag if you're using the "<script setup>" synthax
The issue you are dealing with maybe due to the fact that you're using "useFetch" within the "mounted" hook of Vue.js options API.
But once again, not sure about this one :)

The major difference between useFetch and Axios is that useFetch is a wrapper around useAsyncData (and native $fetch) and so works with both SSR and Static modes of Nuxt.
If using it in the onMounted hook you will probably get more expected results if you set the server option to false so it runs only in the client (more like how Axios runs in the mounted hook). I have predominantly used it in <script setup> for SSR set ups.
More info here: https://v3.nuxtjs.org/api/composables/use-fetch

Related

How to refresh occasional changes with getStaticProps() in next.js? [duplicate]

This question already has answers here:
Next.js ISR ( Incremental Static Regeneration ), how to rebuild or update a specific page manually or dynamically before the interval/ISR time start?
(3 answers)
Closed 8 months ago.
Here's a scenario;
I am adding some static pages in Next.js, so using getStaticProps() sounds good.
But, a user(admin) can also update [from an admin console] the content of these page in future, not very frequently.
So, Is there any way to refresh or re-deploy the pages only after the changes happen?
or, if We can add a button on admin console to refresh/re-deploy after changes!?
Update: All the Page Content is getting stored in Database, and Next.js fetch the data from DB during build process.
My Approach:
use revalidate with getStaticProps(). But, it also doesn't gurantee immediate update, and importantly, causes unnecessary revalidation, as the changes are rare.
Use getServerProps()
As already said, the changes are occasional, it doesn't sounds best to me to use getServerProps().
Thanks!
This is now possible, using On Demand Revalidation, as of NextJS v12.1. However, On Demand Revalidation is still in beta as of the writing of this answer. On Demand Revalidation is documented here. You simply create a revalidation api endpoint and then call it passing a known secret.
Here is the sample api endpoint from the documentation:
export default async function handler(req, res) {
// Check for secret to confirm this is a valid request
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
return res.status(401).json({ message: 'Invalid token' })
}
try {
await res.unstable_revalidate('/path-to-revalidate')
return res.json({ revalidated: true })
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send('Error revalidating')
}
}
Then to force revalidation of the content you would simply call this api endpoint like this:
https://<your-site.com>/api/revalidate?secret=<token>

Resolving an Error 400 with Firebase/Firestore and VueJS

I am attempting to write an ordering app using Google Firebase as the database to store everything. I attempted to test the connection but keep getting GET and POST HTTP 400 errors when I submit test data.
I have installed v8.0.0 via NPM. My firebase.js file is as follows:
import firebase from 'firebase/app'
import 'firebase/firestore'
import { firebaseConfig } from '#/firebaseConfig';
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export const dbMenuRef = db.collection("menu");
Fire security purposes I keep the object Google generates for configuration containing the keys and such in a separate file. I even tried putting the object in the firebase.js file and still got these errors.
The data is structured as follows:
newOrder: {
customerName: 'John Doe',
customerPhone: '1-800-DRUIDIA',
items:[{
itemUPC: '1234567890',
itemDesc: 'A generic item',
itemDist: 'The one we always use'
}, {
itemUPC: '0987654321',
itemDesc: 'Another Generic Item',
itemDist: 'The other one we use'
}]
}
Data is two-way bound to a form. This is working properly and I have the newOrder object displayed in the component. This is working just fine as the JSON looks like above.
The following VueJS method is triggered by clicking a "Submit Order" button.
addOrder() {
dbMenuRef.add(this.newOrder)
}
Edit: I am using Firefox Developer Edition latest version.
Second Edit: This apparently works in Chrome, but not Firefox DE.
It looks like you are passing array as a value to items key. If you use dbMenuRef.add, you might want to add as sub-collections. Instead, you can use .set if you want to have the entire document added (please refer the documentation here. Can you try:
addOrder() {
dbMenuRef
.doc(this.orderID)
.set(this.newOrder)
}

Testing puppeteer with Jasmine?

We have a website that has many paths of flow (login , signup , payment ,etc)
We're using puppeteer scripts ( typescript via node) to automate-testing our website behaviour (full flow) , and when we get an error (or unexpected result) we're sending email or some kind of alerts.
But I see that people also use jasmine with puppeteer.
For example :
const puppeteer = require('puppeteer');
describe("Jasmine puppeteer", function() {
let browser;
let page;
beforeAll(() => {
browser = await puppeteer.launch({headless: false});
page = await browser.newPage();
await page.goto('chrome://newtab');
await page.screenshot({path: 'a.png'});
})
it("jasmine puppeteer", () => {
expect(await page.title()).toBe("");
done();
});
afterAll(() => {
})
});
Using a testing framework over automated testing framework seems (to me) like Test(Test())
Question
Should we change our site approach testing to jasmin over puppeteer ? I mean , currently puepetteer provides a good way to test our site flow. Should we need to apply jasmine testing over our existing tests scripts ? I'm a bit confused about that.
You can use jest with puppeteer for end to end testing. Jest is based on Jasmine framework. It is developed by Facebook and it’s quite popular now.
puppeteer is not a testing framework.
puppeteer is a tool that automate browser.
you cannot make any assert with puppeteer, so you need a testing framework.
a good choise for puppeteer is jest,
because jest come out of the box with everything you need.
you can also use mocha and chai,
but i suggest jest because you can start to use immediately.

Google Map Javascript API in react-native

Is it possible to use the javascript api without entirely being dependent to browser DOM to render the map, since react-native use View I feel it's possible to use the api somehow, The method on which to make the api available by passing to global windows also might be possible using fetch, but I don't know how to initiate the callback. If any one got idea how this can work, please share some thoughts
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
The googlemaps node module #sunilp mentioned only gives you static maps, which are easy to build without relying on a lib, just search for google maps api static maps (don't have enough reputation to post more than two links).
For Android you have this:
https://github.com/teamrota/react-native-gmaps
For iOS there's this, but it cautions it's a work in progress (it also hasn't been updated in months): https://github.com/peterprokop/ReactNativeGoogleMaps
Looking around, it seem your best (supported) bet for iOS today is to use React Native's own MapView if you search their docs. Then, you can make fetch calls to the Google Maps API services for the data, then populate MapView through its interface. Make sure you pass in your key and use https in your url otherwise the service will deny your call:
fetch(
'https://maps.googleapis.com/maps/api/directions/json?origin=41.13694,-73.359778&destination=41.13546,-73.35997&mode=driver&sensor=true&key=[YOUR_KEY]'
)
.then(
(response) => response.text()
)
.then(
(responseText) => {
console.log(responseText);
}
)
.catch(
(error) => {
console.warn(error);
}
);
`
Use node approach of rendering, not yet tried , but looks like it can be done with node-googlemaps
npm install googlemaps
usage
var GoogleMapsAPI = require('googlemaps');
var publicConfig = {
key: '<YOUR-KEY>',
stagger_time: 1000, // for elevationPath
encode_polylines: false,
secure: true, // use https
proxy: 'http://127.0.0.1:9999' // optional, set a proxy for HTTP requests
};
var gmAPI = new GoogleMapsAPI(publicConfig);
you can refer https://github.com/moshen/node-googlemaps

Can I use other node.js libraries in Meteor?

I was playing around with an idea and wanted to get some json from another site. I found with node.js people seem to use http.get to accomplish this however I discovered it wasn't that easy in Meteor. Is there another way to do this or a way to access http so I can call get? I wanted an interval that could collect data from an external source to augment the data the clients would interact with.
Looks like you can get at require this way:
var http = __meteor_bootstrap__.require('http');
Note that this'll probably only work on the server, so make sure it's protected with a check for Meteor.is_server.
This is much easier now with Meteor.http. First run meteor add http, then you can do something like this:
// common code
stats = new Meteor.Collection('stats');
// server code: poll service every 10 seconds, insert JSON result in DB.
Meteor.setInterval(function () {
var res = Meteor.http.get(SOME_URL);
if (res.statusCode === 200)
stats.insert(res.data);
}, 10000);
You can use Meteor.http if you want to handle http. To add other node.js libraries you can use meteorhacks:npm
meteor add meteorhacks:npm
Create apacakges.json file and add all the required packages name and versions.
{
"redis": "0.8.2",
"github": "0.1.8"
}

Resources