I am trying to use the useSWR hook to fetch data from an API.
The API and requests works fine but the data is never updating.
Here is the code:
import useSWR from 'swr'
import { SERVER_URL } from '../config';
import axios from 'axios'
const fetcher = url => axios.get(url).then(res => res.data)
export default function MainPageView() {
const { routines, error } = useSWR(`${SERVER_URL}/api/routines`, fetcher, { refreshInterval: 1000 })
return (...The rest of the component)
When using the routines inside I call it like that {routines?routines:[]}
Thank you for your help and sorry for my english :)
Edited:
I will also mention that if i inspect the page with F12 and go to the network tab, I do see the requests being sent and received with the desired data (with response STATUS 304) but it never updates the routines variable.
Try using const { data: routines, error } = useSWR(...), the data returned by the fetcher function is available in the data property
The answer was given by juliomalves
useSWR hook returns 3 states data, loading and error
try something like this
const { data, error } = useSWR(`${SERVER_URL}/api/routines`, fetcher, { refreshInterval: 1000 })
using data
{data?.properties?.map((item)=>...) }
Related
I implemented a dynamic server side sitemap using next-sitemap package.
And it works smoothly on my local, but when i visit the production sitemap url (https://www.my-url.com/sitemap-dynamic.xml ) it takes too long to load sometimes.
The issue is that the proxy cuts of the request with a 499 response or even 500, after its timeout (30/60 seconds+), resulting in search engines not being able to read the sitemap.
FYI what I did is the same as it's explained in the demo with my customization :
// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndex } from 'next-sitemap'
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// Method to source urls from cms
// const urls = await fetch('https//example.com/api')
return getServerSideSitemapIndex(ctx, [
'https://example.com/path-1.xml',
'https://example.com/path-2.xml',
])
}
// Default export to prevent next.js errors
export default function SitemapIndex() {}
For instance check if we can prewarm the sitemap and refresh it at interval x (hourly/daily ?)
Did someone face or hear about this problem before ? please a hint , and thanks in advance
So far I have been using the following to execute a request against the Graph API.
import { MSGraphClient } from '#microsoft/sp-http';
const graphClient: MSGraphClient = await context.msGraphClientFactory.getClient();
const uriGetAccessPackageAssignmentRequests = `/identityGovernance/entitlementManagement/accessPackageAssignments/filterByCurrentUser(on='target')?$select=id&$expand=accessPackageAssignmentResourceRoles&$filter=assignmentState ne 'Expired'`;
graphClient.api(uriGetAccessPackageAssignmentRequests).version('beta').get();
This has been working without any problems until I decided to change to #pnp/graph in the newest version (3.4.1).
I can use all the preset calls, but I cannot find a way to execute a generic graph call with a custom endpoint.
In all the tutorials they talk about
import { graph } from "#pnp/graph";
But if I do so, I get the following error -> Module '"#pnp/graph"' has no exported member 'graph'.
As I said, the described way in the documentation of using
import { graphfi, GraphFI, SPFx as graphSPFx } from '#pnp/graph'
export const getGraph = (context?: WebPartContext): GraphFI => {
if (_graph === null && context != null) {
//You must add the #pnp/logging package to include the PnPLogging behavior it is no longer a peer dependency
// The LogLevel set's at what level a message will be written to the console
_graph = graphfi().using(graphSPFx(context)).using(PnPLogging(LogLevel.Warning))
}
return _graph
}
is working fine.
I just cannot find anything on how to do a custom endpoint (like the one above) with pnp v3.
Can anyone help here or do I have to stick to the MSGraphClient for that purpose?
Nuxt 3 has those amazing data fetching functions (ex.: useFetch), but I come out on a situation that I need to make request after the rendering time (ex.: calling from a button and send a search term).
As I far know, useFetch are not working on client-side, here is what I have trying to do
<template>
<button #click="goSearch()">Search</button>
</template>
setup() {
const goSearch = async () => {
const { data } = await useFetch('search', () => $fetch('/api/search'));
console.log(data.value);
};
return { goSearch };
},
}
Does nuxt3 offers a built in function to make http request on demand (client-side official http axios like)?
$fetch should work. The problem were a small bug that is now fixed. If you are experiencing this bug, just upgrade nuxt/ohmyfetch lib
npx nuxi upgrade --force
More here:
https://github.com/nuxt/framework/issues/2502#issuecomment-999783226
useFetch is the same as using $fetch, here why not simply use fetch already in your code ?
const { data } = await $fetch('/api/search' );
i think you code is simply no just youcan use useFetch even on client side but like that :
const { data } = await useFetch('/api/search')
I am trying to use Apollo client-state data with the hooks useQuery and useMutation as a global store inside a NextJS app.
When I follow the example from NextJS called with-apollo (https://github.com/zeit/next.js/tree/canary/examples/with-apollo), which uses a HOC in which it runs all the queries and renders the app on the server first.
Normally, you want to catch the 'loading' state in a component like this:
const { loading, data } = useQuery(GET_NAME_QUERY) // some #client query
if (loading) return <p>Loading...</p>
return <h1>Hello {data.name</h1>
But I want to skip the loading-check and always have a default state available. I think this could be done with setting the cache of the apollo-client to a set of default values, like this:
const cache = new InMemoryCache().restore(initialState);
// This is the part where the initial client-state data is set:
cache.writeData({
data: { name: 'Harry' }
});
const apolloClient = new ApolloClient({
cache, // <-- cache with preset client-state data
typeDefs,
resolvers,
})
With the goal to just do this:
const { data } = useQuery(GET_NAME_QUERY) // some #client query, resolves immediately from cache
return <h1>Hello {data.name</h1>
I created a repo with a robot and its name & status that are cached from the beginning this way. See https://github.com/rnacken/next-with-apollo-client-state-cache
The client works, without any errors, but during SSR, I get an error, since it does not have the data yet (and 'loading' is true) after a useQuery call.
When I log the loading/data state, I see this on the server:
On the client, it's all good:
Does anybody know how this is happening? With the cache set, I shouldn't see a loading:true state ever right? Is the getDataFromTree from #apollo/react-ssr not working correctly?
How can I properly simulate a cloud function locally so that it has all data as when being invoked on firebase servers? (e.g. the context.auth)
I am serving my project with firebase serve, it runs ok on http://localhost:5000/, however, my cloud functions are being called from https://us-central1-<my-app>.cloudfunctions.net/getUser. (The function is not even deployed.)
To avoid XY problem, I am trying to debug my function, but calling it from firebase shell results in context.auth being undefined, same when calling via postman from http://localhost:5000/<my-app>/us-central1/getUser.
This is my ./functions/src/index.ts file
import * as functions from 'firebase-functions'
import admin from 'firebase-admin'
import { inspect } from 'util'
admin.initializeApp()
export const getUser = functions.https.onCall((data, context) => {
console.debug('== getUser called =========================================')
console.log('getUser', inspect(data), inspect(context.auth))
return admin.database().ref('userRights/admin').child(context.auth.uid).once('value', snapshot => {
console.log(snapshot.val())
if (snapshot.val() === true) {
return 'OK'
// return {status: 'OK'}
} else {
return 'NOK'
// return {status: 'error', code: 401, message: 'Unauthorized'}
}
})
})
file ./firebase.functions.ts
import { functions } from '~/firebase'
export const getUser = functions.httpsCallable('getUser')
Consumer ./src/pages/AdminPanel/index.tsx
import { getUser } from '~/firebase.functions'
//...
getUser({myDataX: 'asd'}).then(response => console.debug('response', response))
UPDATE - April/2021
As of April/2021, method useFunctionsEmulator has been deprecated. It is suggested to use method useEmulator(host, port) instead.
Original post:
By default, firebase serve sends queries to CLOUD function instead of localhost, but it is possible to change it to to point to localhost.
#gregbkr found a workaround for that at this github thread.
You basically add this after firebase initialization script (firebase/init.js) in html head.
<script>
firebase.functions().useFunctionsEmulator("http://localhost:5001");
</script>
Make sure to REMOVE it when deploying to SERVER
There is currently no support for local testing of callable functions like this. The team is working on a way for you to specify the URL endpoint of a callable function so that you can redirect it to a different location for testing.
Just found a workaround.
using fiddlers AutoResponder to redirect the function call to the local served function.
step 1
copy the target url of the function from the client
step 2
copy the local served function url
step 3
active the auto respoder and use the following rules
(the second rule is also importent to allow all outher requests
That worked for me, thank you #GorvGoyl!
script src="/__/firebase/init.js?useEmulator=true"></script