how to get data from react-query(V4) Promise - react-query

I trying react-query for data-fetching (in Typescipt)
in my books, maybe I guess use react-query V3.
but I want to react-query v4
in my books, using react-query...
const useLatestMovie = () => {
return useQuery<AxiosResponse<MovieDetail>, AxiosError>('latestMovie', latestApi)
}
and call function other files,
const { isLoading, data } = useLatestMovie()
but this code isLiading, data not exist
because "Property 'data' does not exist on type 'Promise'."
how do I make this code can work?

You can type your query functions by just specifying the type with the http request.
In the example below we typed the get request with an array of Users. Because the data is typed and returned in the useQuery hook, typescript will implicitly know the type.
async function fetchUsers() {
const { data } = await http.get<User[]>('/users');
return data;
}
export function useUsers() {
return useQuery(['users'], () => fetchUsers());
}
When we use the useUsers hook in our application, the users variable will be of type Users[]
const { data: users } = useUsers();

I try 2 answer..
using query array...
return useQuery<AxiosResponse, AxiosError>(['latestMovie'], latestApi)
type select
return useQuery<MovieDetail, Error>(['latestMovie'], latestApi)

Related

Single value in ionic http post param

Hi I'm new to ionic/angular and I'm reading someone else code and came across the function below in the Service
makePostRequest(100)
public makePostRequest(param) {
return this.http.post('/sample/api', param);
}
Does this mean param is sent as json body or just a value, online documentation just shows json body as the argument not a single value. Can someone help me with this
Thanks in advance.
The post body is sent as serialized parameters as explained here.
In the example you have provided, they are calling the makePostRequest() function and providing an argument of 100. When the makePostRequest() function runs, it takes that value from the argument and sets it as a parameter which is then used to populate the body in the POST request.
You can still send single values as you would multiple values with something similar to this:
sendData() {
const data = {
number: 100
};
return this.http.post('myurl.com', data);
}
Or for multiple:
sendData() {
const data = {
number: 100,
fruit: 'banana'
};
return this.http.post('myurl.com', data);
}
You can of course pass multiple arguments if you have parameters set up to accept them:
sendData(body: { score: number, fruit: string }) {
return this.http.post('myurl.com', body);
}

Suspense returns data too fast in #tanstack/react-query v4

I am upgrading a React app from react-query v3 to #tanstack/react-query v4.
Almost everything works, but I'm having a problem with Suspense.
I have a react component:
const WrapperPageEdit: React.FC<MyProps> = ({
pageUuid,
redirect,
}: MyProps) => {
const FormPage = React.lazy(() => import('./FormPage'));
const { data } = usePageView(pageUuid);
if (data?.[0]) {
const pageObjectToEdit= data[0];
const content = pageObjectToEdit.myStuff.content;
return (
<Suspense
fallback={<Trans id="loading.editor">Loading the editor...</Trans>}
>
<FormPage
id={uuid}
content={content}
redirect={redirect}
/>
</Suspense>
);
}
return <p>No data.</p>;
};
And here's my query:
export function usePageView(
uuid: string,
): UseQueryResult<DrupalPage[], Error> {
return useQuery<DrupalPage[], Error>(
queryKeyUsePageView(uuid),
async () => {
return fetchAnon(getPageByPageUuid(uuid));
},
{
cacheTime: YEAR_MILLISECONDS,
staleTime: YEAR_MILLISECONDS,
onSuccess: (data) => {
if (data?.[0]) {
data.map((element) => processResult(element));
}
},
},
);
}
This works in v3 but fails in v4 with the following error:
TypeError: Cannot read properties of undefined (reading 'content')
The reason the property is undefined is because that property is set by the processing in onSuccess (data.map).
The issue appears to be that in v4, the component WrapperPageEdit is refreshed before onSuccess in the usePageView query has finished processing, whereas in v3, the component WrapperPageEdit is not refreshed until the onSuccess data.map is complete.
How can I correctly fix this? I can write some additional code to try to check whether the onSuccess data.map is complete, but since react-query handled this automatically in v3, I'd like to rewrite my code in v4 so that it is the same.
The problem is likely that you are mutating the data in onSuccess. Directly modifying data in callbacks is not a good idea. Instead, do your transformation for example directly in the queryFn:
async () => {
const data = fetchAnon(getPageByPageUuid(uuid));
if (data?.[0]) {
data.map((element) => processResult(element));
}
return data
},
other good places to do data transformation is e.g. the select option, but it should always happen in an immutable way, because otherwise, you are overwriting the cached data inadvertently. React prefers updates to be immutable.

Can't access Firestore docs data after getting the doc object

I'm trying to fetch a single field value from a doc in a collection (stored in Firestore).
The following function is called (by the triggered function) to perform this query and return the result.
Firestore data structure:
After I fetch the query result into helper_token object - I cannot access the DATA (fields) in it.
I tried many things, including:
helper_token[0].device_token;
helper_token.data().device_token;
JSON.stringify(helper_token);
Nothing works for me.
The log always shows results like these:
helper_token = {}
helper_token = undefined
What am I missing? how can I get the device_token based on user?
const admin = require('firebase-admin'); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
function getHelperToken(helperId) {
//Get token from Firestore
const tokensRef = db.collection('tokens');
const helper_token = tokensRef.where('user', '==', 'TM1EOV4lYlgEIly0cnGHVmCnybT2').get();
if (helper_token.empty) {
functions.logger.log('helper_token EMPTY');
}
functions.logger.log('helper_token=' + JSON.stringify(helper_token));
return helper_token.device_token;
};
For completeness, adding here the full calling function to the above function:
//DB triggered function - upon writing a child in the HElpersInvitations reference
exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
.onCreate((snapshot, context) => {
const helperId = snapshot.val().helperId;
const title = snapshot.val().title;
const body = snapshot.val().body;
//Get the helper token by Id
functions.logger.log('HelperID=' + helperId);
functions.logger.log('getHelperToken=' + getHelperToken(helperId));
const helper_token2 = getHelperToken(helperId);
//Notification payload
const payload = {
notification: {
title: title,
body: body,
icon: 'default',
click_action: 'com.skillblaster.app.helperinvitationnotification'
}
}
// //Send the notification
functions.logger.log('helper_token [BEFORE sendToDevice]=' + helper_token2);
return admin.messaging().sendToDevice(helper_token2, payload);
});
You need to consider that the get() call is asynchornous and also that you get a list of documents and not a single doc. Can you try it with this code:
const admin = require("firebase-admin"); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
async function getHelperToken(helperId) {
//Get token from Firestore
const tokensRef = db.collection("tokens");
const helperTokens = await tokensRef
.where("user", "==", "TM1EOV4lYlgEIly0cnGHVmCnybT2")
.get();
let helper_token = "";
helperTokens.forEach((token) => {
helper_token = token.data();
});
functions.logger.log("helper_token=" + JSON.stringify(helper_token));
return helper_token.device_token;
}
As the get() call in Firestore is asynchronous you need to use an asynchronous function. You can go through this article to know more about why Firebase APIs are asynchronous. Next when we query with the where clause in Firestore we get a list of documents even if there is only one document in the list. So we have to run a for loop to get the document inside the list of documents. Now as you are returning the value from an asynchronous function the return value will be a promise in pending state. So to get the value from the promise we need to use the then() block while calling the function.
Also I think the parameter helperId you are using in the function definition is not used anywhere in the function. Though it will not make a difference I would suggest you remove it if it is not required in the function.
So consider using the following code -
const admin = require(‘firebase-admin’);
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
async function getHelperToken() {
//Get token from Firestore
const tokensRef = db.collection(‘tokens’);
const helper_token = await tokensRef.where(‘user’, ‘==’, ‘TM1EOV4lYlgEIly0cnGHVmCnybT2’).get();
let helper_token_needed;
helper_token.forEach((token) => {
helper_token_needed = token.data();
});
console.log(helper_token_needed.device_token);
return helper_token_needed.device_token;
}
//when calling to the function use then() block to get the value as a promise is returned from asynchronous function
getHelperToken().then((value)=>{console.log(value)});

Using Restangular, can I use a jsonResultsAdapterProvider when needing to override the id field?

I've got a mySql db with non-standard IDs and field names, so I was trying to use both jsonResultsAdapterProvider and setRestangularFields. Here's the code in my app.config file:
RestangularProvider.setBaseUrl(remoteServiceName);
RestangularProvider.setRestangularFields({id: 'personID'});
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (data.error) {
return data.error;
}
var extractedData = data.result;
return jsonResultsAdapterProvider.$get().camelizeKeys(extractedData);
});
RestangularProvider.addRequestInterceptor(function(elem, operation, what, url) {
return jsonResultsAdapterProvider.$get().decamelizeKeys(elem);
});
It's all good until I try to do a put/save. When I look at the request payload within the browser dev tools, it's: {"undefined":12842} (but the url is correct, so I know the id is set) If I don't use the ResultsAdapter and change the id field to Person_ID, payload looks good, so I know I'm making the right calls to Get and Save the Restangular objects. But for what it's worth, here's the code:
$scope.tests = Restangular.all('members').getList().$object;
vm.testEdit = function () {
$scope.test = Restangular.one('members', 12842).get().then(function(test) {
var copy = Restangular.copy(test);
copy.title = 'xxxx';
copy.put(); // payload was: undefined: 12842
});
}
// I also tried customPUT...
// copy.customPUT(copy, '', {}, {'Content-Type':'application/x-www-form-urlencoded'});
I tried "fixing" the id other ways too, too. like this:
Restangular.extendModel('members', function(model) {
model.id = model.personID;
return model;
});
but that messed up the urls, causing missing ids. And I tried getIdFromElem, but it only got called for my objects created with Restangular.one(), not with Restangular.all()
Restangular.configuration.getIdFromElem = function(elem) {
console.log('custom getIdFromElem called');
if (elem.route === 'members') { // this was never true
return elem[personID];
}
};
It seems like Restangular needs to substitute 'personID' most of the time, but maybe it needs 'Person_ID' at some point during the Save? Any ideas on what I could try to get the Save working?
I finally figured it out! The problem was in my config code and in the way I was decamelizing. Because of inconsistencies in my db field names (most use underscores, but some are already camelCase), I was storing the server's original elem names in an array within the jsonResultsAdapterProvider. But since I was calling jsonResultsAdapterProvider.$get().camelizeKeys(extractedData); within the interceptors, I was reinstantiating the array each time I made a new request. So, the undefined in the PUT request was coming from my decamelizeKeys() method.
My updated config code fixed the problem:
RestangularProvider.setBaseUrl(remoteServiceName);
RestangularProvider.setRestangularFields({id: 'personID'});
var jsonAdapter = jsonResultsAdapterProvider.$get();
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (data.error) {
return data.error;
}
var extractedData = data.result;
// return extractedData;
return jsonAdapter.camelizeKeys(extractedData);
});
RestangularProvider.addRequestInterceptor(function(elem, operation, what, url) {
return jsonAdapter.decamelizeKeys(elem);
});

Caching a result from EF

I have this method for retrieving a result from my context and caching it using MemoryCache.
public IEnumerable<CustomerRole> GetCustomerRoles()
{
string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all");
return _cacheManager.Get(key, () =>
{
return from r in _customerRoleRepository.Table select r;
}
);
}
I then use this in my view like
#foreach (CustomerRole role in Model)
{
}
The problem I have is that because the actual result isn't executed until the data is accessed (in my view), it's not actually caching the result.
How do I force this query to run via my caching function rather than waiting until the data is used?
I've not included what _cacheManager.Get() does as I know it's caching whatever I send to it properly but if you think that is the problem, let me know and I will post the relative code.
Note: I have tried doing it this way hoping it would force the query to run but still no luck
public IEnumerable<CustomerRole> GetCustomerRoles()
{
string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all");
return _cacheManager.Get(key, () =>
{
var roles = from r in _customerRoleRepository.Table select r;
return roles.Take(roles.Count());
}
);
}
You need to call a method like ToList() to force linq to get the data. Then just add that list to your cache.