The arguement passed inside a function becomes undefined - javascript

const onCellClick = p => {
const policyId = p?.id;
const updatedBy = p?.row?.updated_by;
console.log(updatedBy, "updatedBy");
applyPolicies(policyId, updatedBy);
};
This is the another function where I am doind API call with pID and updatedBy, the updatedBy becomes undefined where pID is fine.
export const useApplyPolicyMutation = () => {
return useMutation(
(pID, updatedBy) => {
console.log(updatedBy, "updatedByinquery");
console.log(pID, "pID");
const workspaceId = getWS();
const payload = {
workspace_id: workspaceId,
policy_id: pID,
updated_by: updatedBy
};
customPost("/policymanagement/api/v1/auto-discover/add-policy", payload);
}

useMutation can only take one argument as payload, so you need to wrap it in an object:
export const useApplyPolicyMutation = () => {
return useMutation(
- (pID, updatedBy) => {
+ ({ pID, updatedBy }) => {
- applyPolicies(policyId, updatedBy);
+ applyPolicies({ pID: policyId, updatedBy });

Related

How to pass more parameters in useInfiniteQuery?

I am using React query useInfiniteQuery to get more data
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", listofSessions, {
getNextPageParam: (lastPage, pages) => {
if (lastPage.length < 10) return undefined;
return pages.length + 1;
},
});
API requests:
const listofSessions = async ({ groupId, pageParam = 1 }) =>
await axios
.get(`${apiURL}/groups/allsessions`, {
params: {
groupId: 63,
page: pageParam,
},
})
.then((res) => {
return res.data.data;
});
I want to pass groupId to listofSessions API function like that:
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", listofSessions({groupId}), ....
But I get an error
Missing queryFn
How can I solve this problem of passing multiple parameter values in useInfiniteQuery?
Does passing a new function work?
const listofSessions = async ({ groupId, pageParam = 1 }) =>
await axios
.get(`${apiURL}/groups/allsessions`, {
params: {
groupId: 63,
page: pageParam,
},
})
.then((res) => {
return res.data.data;
});
// pass a new function
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", ({ pageParam = 1 }) => listofSessions({ groupId, pageParam}), {
getNextPageParam: (lastPage, pages) => {
if (lastPage.length < 10) return undefined;
return pages.length + 1;
},
});
Edit: Please include dependencies in the query key InfiniteQuery(["listofSessions", groupId, moreSearchParams], so that the cache is valid for the search parameters. Thanks #TkDodo for pointing it out and improving the answer
If it is possible to refer to groupId inside listofSessions that would be a simpler solution.

When I log Array there's an object inside, but when I'm trying to access that object it returns me undefined

This is my cache "component":
// imports
const useCache = (cacheName: string, url: string) => {
const cacheArray: Array<Object> = []
const getAllCaches = async () => {
const cacheNames = await caches.keys();
for (const cname of cacheNames) {
const cacheStorage = await caches.open(cname);
const cachedResponse = await cacheStorage.match(url);
const cdata = await cachedResponse?.json()
cacheArray.push({name: cname, data: cdata})
}
}
useEffect(() => {
getAllCaches()
.catch(err => console.log(err))
}, [])
const addCache = (response: any) => {
const data = new Response(JSON.stringify(response));
if ('caches' in window) {
caches.open(cacheName).then((cache) => {
cache.put(url, data);
});
}
const finalData = {name: cacheName, data: response}
cacheArray.push(finalData)
return data
}
const getCache = (cacheName?: string) => {
if (cacheName) {
return cacheArray.filter((i: any) => i.name === cacheName)[0]
}
else {
return cacheArray
}
}
const removeCache = (cacheName: string) => {
caches.delete(cacheName).then(function (res) {
return res;
});
}
return [
getCache as (cacheName?: any) => any,
addCache as (response: any) => any,
removeCache as (cacheName: any) => any
]
};
export default useCache;
Now here's code in my home component:
const [getCache, addCache, removeCache] = useCache("user", "http://localhost:3000")
useEffect(() => {
console.log(getCache())
console.log(getCache()[0])
console.log(getCache().length)
// the rest of code, not matter
and when I run home component (with vite and preact) it logging me Array, then unfedinfed, then 0 (but second should return object, and third should return 1) also I attached a screen from console.
Why it's returning me undefined and 0 length when it should return object and 1?
I'm using preact, vite, newest nodejs, typescript

react-query 3 setQueryData doesn't update the cache

I have this query:
export function useCardList() {
return useQuery(['cardList'], fetchCardList());
}
I'm using it in my component:
const { data, isLoading } = useCardList();
// delete
const handleOnDelete = (id: string) => {
const newData = {
...data,
data: data?.data.filter((card) => card.id !== id)
};
queryClient.setQueryData(['cardList'], newData);
};
but setQueryData doesn't work. what do you think? (edited)

Trying to understand an object composition pattern which features a factory and a function based mixin technique

I'm trying to understand behavior of function based composition in JavaScript.
const Animal = (name) => {
let properties = { name };
return ({
get name() { return properties.name },
set name(newName) { properties.name = newName },
breathe: function() {console.log(`${this.name} breathes!`); }
})
}
const aquaticKind = (animal) => ({
swim: () => console.log(`${animal.name} swims`)
})
const walkingKind = (animal, noOfLegs) => {
const properties = { noOfLegs }
return ({
get noOfLegs() { return properties.noOfLegs },
set noOfLegs(n) { properties.noOfLegs = n; },
walk: () => console.log(`${animal.name} walks with ${properties.noOfLegs} legs`)
})
}
const egglayingKind = (animal) => ({
layEgg: () => console.log(`${animal.name} laid an egg`)
})
const Crocodile = (name) => {
const info = Animal(name);
return Object.assign(info,
walkingKind(info, 4),
aquaticKind(info),
egglayingKind(info)
);
}
const snooty = Crocodile('snooty');
snooty.breathe();
snooty.swim();
snooty.walk();
snooty.name = "coolie";
snooty.noOfLegs = 23 // I expected this to get update to 23
snooty.swim();
snooty.walk();
snooty.layEgg();
If you run the code above, you will see that noOfLegs never get updated, while name get updated. I can't seem to wrap my head around this. How do we make noOfLegs get updated too?
MDN Documentation for object.assign shows you how to copy "accessors"
Here's your code that works as expected - the completeAssign function is based entirely on the code in that link
const completeAssign = (target, ...sources) => {
sources.forEach(source => {
const descriptors = Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {});
Object.getOwnPropertySymbols(source).forEach(sym => {
const descriptor = Object.getOwnPropertyDescriptor(source, sym);
if (descriptor.enumerable) {
descriptors[sym] = descriptor;
}
});
Object.defineProperties(target, descriptors);
});
return target;
};
const Animal = (name) => {
const properties = { name };
return ({
get name() { return properties.name },
set name(newName) { properties.name = newName },
breathe () { console.log(`${this.name} breathes!`); }
})
}
const aquaticKind = (animal) => ({
swim: () => console.log(`${animal.name} swims`)
});
const walkingKind = (animal, noOfLegs) => {
const properties = { noOfLegs };
return ({
get noOfLegs() { return properties.noOfLegs },
set noOfLegs(n) { properties.noOfLegs = n; },
walk: () => console.log(`${animal.name} walks with ${properties.noOfLegs} legs`)
})
}
const egglayingKind = (animal) => ({
layEgg: () => console.log(`${animal.name} laid an egg`)
})
const Crocodile = (name) => {
const info = Animal(name);
return completeAssign(info,
walkingKind(info, 4),
aquaticKind(info),
egglayingKind(info)
);
}
const snooty = Crocodile('snooty');
snooty.breathe();
snooty.swim();
snooty.walk();
snooty.name = "coolie";
snooty.noOfLegs = 23;
snooty.swim();
snooty.walk();
snooty.layEgg();

keep getting empty result on my previous promise

this.state = {
city: null,
cityNumber : null,
typeWeather: "",
minTemp: 0,
maxTemp: 0,
theTemp: 0
};
}
SearchingCity = (city) => {
return new Promise(resolve => {
axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/search/?query=${city}`)
.then((result) => {
let cityName = result.data[0].woeid;
this.setState({
city: cityName
});
resolve(cityName)
})
})
}
getCityID = async () => {
const cityID = await this.SearchingCity();
console.log(cityID)
this.setState({
cityNumber : cityID
})
const thisID = this.state.cityNumber;
axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${thisID}`)
.then((result) => {
const type_Weather = result.data.consolidated_weather[0].weather_state_name
const min_Temp = result.data.consolidated_weather[0].min_temp
const max_Temp = result.data.consolidated_weather[0].max_temp
const the_Temp = result.data.consolidated_weather[0].the_temp
this.setState({
typeWeather : type_Weather,
minTemp : min_Temp,
maxTemp : max_Temp,
theTemp : the_Temp
})
})
}
so in the console.log(cityID) it's supposed to be the result from SearchingCity method, but
when i console.log(cityID), i got the empty result, where is the part i should change?
thank you guys
as #gbalduzzi pointerd out,
The Problem is here,
const cityID = await this.SearchingCity();
// ^^
Your not calling SearchingCity with any city parameter as needed in,
SearchingCity = (city) => {
// ^^^^^^

Categories

Resources