How to use remove() (Firebase SDK 9 web) - react-native

How to use "remove()" in SDK v9 web?
(context: I'm learning React Native (using Expo) and there's this todo app).
There are no examples in the documentation. Here is what I have:
// firebase
import app from "./firebaseConfig";
import {
getDatabase,
ref,
set,
push,
onValue,
remove,
child,
} from "firebase/database";
// etc
const db = getDatabase(app);
const taskListRef = ref(db, "tarefas/" + user);
const newTaskRef = push(taskListRef);
// etc
const handleDelete = (key) => {
remove(taskListRef).then(() => {
const findTasks = tasks.filter((item) => item.key !== key);
setTasks(findTasks);
});
};
So, this remove(taskListRef) is my problem. I don't know how to call it properly regarding the reference to the data location.
I've tried: remove(taskListRef.child(user)), remove(taskListRef.child(key)) etc... and a bunch of other similar things. The error always: wrong reference.
Here is the repo. Please, help. Thank you all in advance.
P.S.: hopefully I won't have to ask a similar question regarding update().

Related

React Native cheerio.load() not working properly neither is JSDOM library

Well I'm new to this app development thing especially react-native and I wanted to know when I'm trying to scrap a website using cheerio and axios in react-native and then save it to firebase realtime database in the following way:
and yes i have done all the imports and also initalized my app using firebaseConfig
const db = firebase.database();
async function loadFurniture() {
const Url = 'https://hoid.pk/product-category/bedroom/beds-bedroom/';
const html = await axios.get(Url); // fetch page
const $ = cheerio.load(html); //parse html String
const furniture = [];
$('.product-wrapper ').each((i, element) => {
const title = $(element).find('h2.product-name').text();
const imageUrl = $(element).find('img.primary_image').attr('src');
const price = $(element).find('span.woocommerce-Price-amount amount').text();
console.log(title);
furniture.push({ title, imageUrl, price });
});
// Save the furniture to the Firebase Realtime Database
db
.ref('/furniture/bed')
.set({
title: furniture.title,
price: furniture.price,
object_image : furniture.imageUrl,
})
.then(() => console.log('Data set.'));
console.log(furniture);
// Return the extracted information
return furniture;
}
and then calling this function in a button
<Button
title="Fetch"
onPress = {() => loadFurniture() }
/>
The data was not being scraped so I tried to console.log() the data being fetched.
Whenever I click the button there is no error but just a log [ Function initialize ] with respect to console.log(title)
And before anyone says yup I've looked into the structure and 9it does returns me my desired classes after axios.get()
I just want to know that if there's some error in my code or if I'm going wrong somewhere.
I tried to scrap furniture titles, images and prices from certain website and then save it to database for any further use but it's just not working.
I've checked my network issues the html page being scraped and everything else one can think of. Now i just want to know either my code is accurate or if there's some mistake.
I tired to scrap the data of same website using python and it scraps it perfectly.
Edit:
I found out that the cheerio.load() function is not working there was no problem with the database... Is there some problem with cheerio.load() in it's latest version "1.0.0-rc.12" ?? If so what's the solution... I've tried number of libraries and each is giving a different kind of error so cheerio might be the only possible solution so if there's an alternative way of using cheerio.load() in react native do let me know.

Add CoreUI icon to DevExtreme dxDataGrid column header in Vue.js

Currently I am working on a new UI for a legacy API. Unfortunately, this one delivers HTML source code for a column header. This code usually creates a FontAwesome icon. This library will not be used in the new project.
I found a very similar icon in the Icon Library of CoreUI. Now it is only a matter of rendering the icon at this point. However, no approach has been successful so far. How can I replace the icon in the headerCellTemplate method?
Or maybe there is a completely different, much better approach to do this. I don't know if I am on the right track with this method approach. You can probably use static templates, but I don't know how to do that.
import { CIcon } from '#coreui/vue';
import { cilCheckCircle } from '#coreui/icons';
headerCellTemplate: (element, info) => {
element.innerHTML = curr.ColumnTitle;
if (element.firstChild.nodeName === 'I') {
// WORKS
//element.firstChild.innerHTML = 'Done';
// ANOTHER EXPERIMENT
//const componentClass = Vue.extend(cilCheckCircle);
//const instance = new componentClass();
//instance.$mount();
//element.removeChild(element.firstChild);
//element.appendChild(instance.$el);
// ALSO NOT WORKING
return CIcon.render.call(this, cilCheckCircle);
}
}
I finally found a solution after revisiting this interesting article.
import Vue from 'vue';
import { CIcon } from '#coreui/vue';
import { cilCheckCircle } from '#coreui/icons';
headerCellTemplate: (element, info) => {
element.innerHTML = curr.ColumnTitle;
if (element.firstChild.nodeName === 'I') {
const cIconClass = Vue.extend(CIcon);
const instance = new cIconClass({
propsData: { content: cilCheckCircle }
});
instance.$mount(element.firstChild);
}
}
I don't know, though, if this is the ideal solution. So feel free to tell me, if you have a better, less complex solution.

data not fetching from firestore in react native

i created a collection in firestore called user and added a document and gave it 7 fields, but when i try fetching the data back using onSnapshot it does not return back any data. this is the collection
this is my code:
firestore()
.collection('user')
.doc('LCqSZXM17WUWiWFahyj6')
.onSnapshot((row) => {
console.log(row.data());
});
in the console it logs an empty array
thanks in advance!!!
You need to include more information.
Anyway, do you check your access rule of the Firestore database?
const doc = db.collection('cities').doc('SF');
const observer = doc.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
// ...
}, err => {
console.log(`Encountered error: ${err}`);
});
The above code is official docs code. Check error callback first.

How to handle deep linking in react native / expo

I have posted about this previously but still struggling to get a working version.
I want to create a sharable link from my app to a screen within my app and be able to pass through an ID of sorts.
I have a link on my home screen opening a link to my expo app with 2 parameters passed through as a query string
const linkingUrl = 'exp://192.168.0.21:19000';
...
_handleNewGroup = async () => {
try {
const group_id = await this.createGroupId()
Linking.openURL(`${linkingUrl}?screen=camera&group_id=${group_id}`);
}catch(err){
console.log(`Unable to create group ${err}`)
}
};
Also in my home screen I have a handler that gets the current URL and extracts the query string from it and navigates to the camera screen with a group_id set
async handleLinkToCameraGroup(){
Linking.getInitialURL().then((url) => {
let queryString = url.replace(linkingUrl, '');
if (queryString) {
const data = qs.parse(queryString);
if(data.group_id) {
this.props.navigation.navigate('Camera', {group_id: data.group_id});
}
}
}).catch(err => console.error('An error occurred', err));
}
Several issues with this:
Once linked to the app with the query string set, the values don't get reset so they are always set and therefore handleLinkToCameraGroup keeps running and redirecting.
Because the URL is not an http formatted URL, it is hard to extract the query string. Parsing the query string returns this:
{
"?screen": "camera",
"group_id": "test",
}
It doesn't seem right having this logic in the home screen. Surely this should go in the app.js file. But this causes complications not being able to use Linking because the RootStackNavigator is a child of app.js so I do not believe I can navigate from this file?
Any help clarifying the best approach to deep linking would be greatly appreciated.

React Native + Redux: Where to put functions for 3rd party libraries?

I'm creating an ecommerce app that uses a geolocation library (https://github.com/transistorsoft/react-native-background-geolocation).
I have an orderState:
const ordersInitState = {
lineItems: [],
status: ORDER_STATUSES.AWAITING_CHECKOUT,
};
const ordersReducer = (prevState=ordersInitState, action) => {
switch(action.type) {
...
case actions.ORDERS.REMOVE_ITEM:
const lineItems = [...prevState.lineItems];
const indexToRemove = action.payload;
lineItems.splice(indexToRemove, 1);
const status = lineItems.length > 0 ? prevState.status : ORDER_STATUSES.AWAITING_CHECKOUT;
return {
...prevState,
status,
lineItems,
};
default:
return prevState;
}
}
export default ordersReducer;
As you can see, the client is allowed to remove items from their cart. If they end up removing everything, their order status will reset. If they do end up emptying their cart (lineItems.length === 0) I want to also run a simple line from the geolocation library:
BackgroundGeolocation.removeGeofence("blah");
Where would I put this? It feels wrong to do it in the reducer because it has nothing to do with state. It also isn't specific to one particular component, so putting it in one of my components doesn't make sense.
I'm still a bit new to redux so I'm not sure where to put non-state related methods.
The often used name for what you are looking for is called "side effects" middleware. In the abstract, you want to cause an effect in an external system (in this case, the geolocation library), when the application state changes.
There are many libraries for this use case. Some of the more popular ones are redux-saga and redux-loop. They are both good tools and help give structure to managing complicated side effects, but both come with a significant conceptual overhead, and should only be used when really needed.
If you want a quick and simple solution, you can create a plain JavaScript module that subscribes to your store changes and executes the side effects for you:
import store from '../your/redux/store;
let previousCount = 0;
store.subscribe(() => {
const count = store.getState().orders.lineItems.length;
if (count === 0 && previousCount > 0) {
// someone just emptied the cart, so execute side-effect
BackgroundGeolocation.removeGeofence("blah");
}
previousCount = count;
});
And then if you find yourself needing this type of solution repeatedly, you can reach for one of the libraries mentioned above.