recently I've just started to read RTK Query's document in the redux.js.org and understood the doc's main project doesn't show the Posts in CodeSandbox and just [object Object] is obvioused except of the Posts list which should being loaded by the fake server included in the default project .
secondly I couldn't managed the error in PostsList page (the Page which is included in the redux main project (simple social media)) .
features/posts/PostsList.js
export const PostList = () => {
const {
data: posts = [],
isSuccess,
isLoading,
isError,
error,
} = useGetPostsQuery()
const orderedPosts = useMemo(() => {
console.log(posts)
const ordered = posts.posts.slice()
ordered.sort((a, b) => b.date.localeCompare(a.date))
return ordered
}, [posts])
just got the [] as the posts value then this error appears "Cannot read properties of undefined (reading 'slice')"
and the whole the main project of redux is accessible right in this link
rtk-query-basics
I believe the problem is in the following line:
const ordered = posts.posts.slice()
It is trying to access a posts property on the posts array, which returns undefined (most likely a typo). This would explain the error message, as undefined is not an array, and therefore does not have a slice method.
To fix the problem, amend the line to look like this:
const ordered = posts.slice()
Related
I followed the tutorial yet this error isn't being solved](https://i.stack.imgur.com/2qNEF.jpg)
I tried to use {} instead of [] but still the same error occurs
your useContext return null. And you try to destructure null. If you don't provide array in context provider value then you can't write:
const [a1, a2] = ....
So probably you miss match useState
const [state, setState] = useState
with context
const context = useContext(Context)
So. Just write:
const balance = useContext(BalanceContext);
console.log('balance context:',balance)
and then you will see what is in balance context.
if is a object then you have to destructure object.
ps.
quick fix to run project:
const [balance, setBalanace] = useContext(BalanceContext) || [];
// balance and setBalance is undefined
I am working on react native application I use firebase as my backend. I fetch data from firebase real time database and render it on the page. But now I want my application to be supported offline.
I used following two functions for rendering.
For listings from database
const loadListings = () => {
let data = [];
listingRef.orderByChild("created_at").on("value", (snapshot) => {
data = [];
snapshot.forEach((listing) => {
data.push(listing.val());
});
cache.store("listings", data.slice(0, 10)); // only stores latest ten listings
setListings(data);
setLoading(false);
});
};
and then use it inside useEffect like.
useEffect(() => {
loadListings();
}, []);
and for listings from cache I used this.
const loadListingsCached = async () => {
let data = await cache.get("listings");
setListings(data);
};
Now I cant put a check inside firs function as effect hook will run only one time and initialy network status is null. its not defined.
how do I achieve this?
by the way link to package I used for detecting connectivity
Edit
I used this hook as second argument to useEffect() but didn't work for me
const netInfo = useNetInfo();
I
What you want to achieve is make the code different depending on what is the network status. In the answer linked by #Rohit there is my answer about how to check the network connectivity with Net Info Package.
What you have to do is make the effect dependant on the status change. You should pass it as a argument to the effect.
const netInfo = useNetInfo();
useEffect(() => {
loadListings();
}, [netInfo]);
This way the code will always run when a network change is detected. I hope this is what you wanted to achive. Please be more specific about you goal and what is the problem. Current questions does not specify if the hook is not working, or the rendering function does not trigger etc.
I'm trying to use the amazing features brought by the Custom Template on Google Tag Manager to organize the tags we use to log events on Amplitude.
I used to have a code like : amplitude.getInstance().logEvent(eventTitle, {args})
However, due to sandbox javascript we do not have direct access to amplitude.
So I tried to do:
const callInWindow = require('callInWindow');
const copyFromWindow = require('copyFromWindow');
const amplitude = copyFromWindow('amplitude');
callInWindow('amplitude.getInstance().logEvent', eventTitle, args);
And I gave full permissions on :
amplitude
amplitude.getInstance
amplitude.getInstance.logEvent
But the result is a tag failing with error saying : Tag XXX threw an error
The only workaround I found is to use a deprecated version of the API: amplitude.logEvent in the following way.
const callInWindow = require('callInWindow');
const copyFromWindow = require('copyFromWindow');
const amplitude = copyFromWindow('amplitude');
callInWindow('amplitude.logEvent', eventTitle, args);
And it works properly but I don't know for how long based on the deprecation announced by Amplitude : https://amplitude.github.io/Amplitude-JavaScript/Amplitude#amplitudelogevent
Does anyone know how I could in js sandbox first get the instance of amplitude.getInstance and then call used it's logEvent feature?
Your help would be highly appreciated.
Cheers!
Does this code fix your issue?
const callInWindow = require('callInWindow');
const args = data.args.reduce((result, item) => {
result[item.key] = item.value;
return result;
}, {});
const amplitudeInstance = callInWindow('amplitude.getInstance');
amplitudeInstance.logEvent(data.eventTitle, args);
data.gtmOnSuccess();
You will need a text field called eventTitle and a table called args with key and value text columns for this code to work.
The template needed execute permissions for amplitude.getInstance, but that was all.
Basically, I'm trying to replicate my data that's already in firebase into algolia through firebase cloud functions. The code doesn't compile and I can't seem to figure out why.
I'm using typescript, not javascript and am following this article right here.
https://medium.com/#soares.rfarias/how-to-set-up-firestore-and-algolia-319fcf2c0d37
I'm also working in VScode
// This is at the top of my file
const algoliasearch = require('algoliasearch')
const algoliaClient =
algoliasearch(functions.config().algolia.appid,
functions.config().algolia.apikey)
export const sendCollectionToAlgolia =
functions.https.onRequest(async (req, res) =>
{
const collectionIndex = algoliaClient.initIndex('Organizations')
const db = admin.firestore()
const algoliaRecords = []
const querySnapshot = await db.collection("Organizations").get()
querySnapshot.docs.forEach(doc => {
const document = doc.data()
const record = {
objectID: doc.id,
"orgUsername": document.orgUsername,
"orgName": document.orgName,
"school": document.school
}
algoliaRecords.push(record)
})
collectionIndex.saveObjects(algoliaRecords, (_error: any, content:
any) => {
res.status(200).send("COLLECTION was indexed to Algolia
successfully.");
})
})
I keep getting the compile error that says "Variable 'algoliaRecords' implicitly has type 'any[]' in some locations where its type cannot be determined" and I do not know how to fix it. I'm relatively new to algolia but have been doing cloud functions for a little bit.
This happens because algoriaRecords does not have an explicit type. Typically, TypeScript will infer types based on what you end up assigning later on. However, each subsequent algoriaRecords.push() operation evolves the type of the variable in accordance with the elements added to it.
A quick fix to this is by explicitly giving a type to algoriaRecords like such:
const algoriaRecords:Object[] = []
Furthermore, you can make TypeScript tolerate params with no types declared, see here for more information by configuring your tsconfig.js file and settting the noImplicitAny to false while removing the strict rule
// "strict": true
"noImplicitAny" : false
I have refactor problems because my code dosnt work to the new versions of angular and angularfire.
Error
The line: upload.url = uploadTask.snapshot.downloadURL; is undefined.
Code
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
// three observers
// 1.) state_changed observer
(snapshot) => {
// upload in progress
upload.progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
console.log(upload.progress);
},
// 2.) error observer
(error) => {
// upload failed
console.log(error);
},
// 3.) success observer
(): any => {
upload.url = uploadTask.snapshot.downloadURL; //?!?!UNDEFINED
upload.name = upload.file.name;
this.saveFileData(upload);
}
);
Questions
I had tried different solutions from stackoverflow but it dosnt really work. Most of the example is also more about how to retrieve the image but i want to set the variable upload.url to a value.
Another question:
I'm new to angular and web. Will it take long time to change it to firestore? The code is based on realtime firebase.
To get the downloadURL, you have to call the getDownloadURL() method of the Storage Reference Object.
Try this:
uploadTask.snapshot.ref.getDownloadURL()
.subscribe(url => console.log(url))