Trouble Deleting in React Native Firebase Firestore - ios

I am trying to delete an object within a firebase firestore database. This was built in react native expo. When I run the code shown below, the console displays "Doc deleted", however, The object I meant to delete still shows in firebase as well as within my applicaton. Any advice would be greatly appreciated.
async function deleteProperty() {
await firebase.firestore().collection("Properties").get().then((documentSnapshot => {
documentSnapshot.forEach((doc) => {
if (doc.data().address == route.params.address) {
firebase.firestore().collection("Properties").doc().delete().then(() => {
console.log("Doc deleted")
}).catch((error) => {
console.error("Error removing document: ", error)
})
}
})
}))
}

It looks like you have to pass document id to doc() specifically.
firebase.firestore().collection("Properties").doc(doc.id).delete().then(() => {
console.log("Doc deleted")
}).catch((error) => {
console.error("Error removing document: ", error)
})
ref: https://firebase.google.com/docs/firestore/manage-data/delete-data#web-version-8

Related

I don't get the "onPushTokenReceivedCallback when" i use my phone

I dont get the token when i use my iphone. I get the token when i use the simulator.
I use nativescript-firebase-plugin and in main.js i do the firebase.init functions.
I have tried with everything i have found on this error, or i dont even know if its a common error. The full init looks like this
firebase.init({
showNotifications: true,
showNotificationsWhenInForeground: true,
onPushTokenReceivedCallback: (token) => {
console.log(`onPushTokenReceivedCallback: ${token}`);
appSettings.setString('firebasemessagekeytoken', token);
},
onMessageReceivedCallback: (message) => {
console.log(`onPushTokenReceivedCallback: ${message.title}`);
}
})
.then(() => {
console.log('[Firebase] Initialized');
})
.catch(error => {
console.log(`error: ${error}`);
});```

axios-on-rails, how to request set of records

I'm creating an app in Rails with a ReactJS front-end. In my front-end I'm using the axios-on-rails yarn package to make all my requests to my Rails api back-end.
Heres what I'm trying to do: for the main page of the site I want to implement an infinite scroll feature. For that to work well I need to be able to request small sets of records as the page continues to scroll. The only way I know how to pass records to my front-end is using:
axios.get('/posts.json')
.then((response) => {
...
})
.catch(error => console.log(error));
This returns ALL posts though, which eventually will be thousands. I don't want that happening. So how do I modify this request so that I only get the first 20 records or so?
Answer Details
Okay so I took a second look at pagination as #Gagan Gupta suggested and after a few hours got it to work. Heres what I did.
yarn add react-infinite-scroll to get the component needed.
For my feed component I did...
import React from 'react';
import Post from './Post';
import { connect } from 'react-redux';
import { loadPosts } from '../actions/posts';
import InfiniteScroll from 'react-infinite-scroller';
import axios from 'axios-on-rails';
const node = document.getElementById('owc_feed_payload');
const numberOfPosts = JSON.parse(node.getAttribute('number_of_posts'));
class Feed extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: props.posts,
hasMoreItems: true,
page: 1
};
}
componentDidUpdate(prevProps) {
if (this.props !== prevProps) {
this.setState({ posts: this.props.posts, hasMoreItems: this.props.hasMoreItems });
}
}
loadMore = (page) => {
axios.get('/posts.json', {
params: { page: page }
})
.then((response) => {
console.log(response.data);
this.props.dispatch(loadPosts(response.data));
this.setState({ hasMoreItems: this.state.posts.length < numberOfPosts ? false : true, page: this.state.page + 1 });
})
.catch(error => console.log(error));
}
render() {
let items = [];
this.state.posts.map((post, index) => {
items.push(
< ... key={index}>
...
</...>
);
});
return (
<InfiniteScroll
pageStart={0}
loadMore={this.loadMore}
hasMore={this.state.hasMoreItems}
loader={<p>Loading...</p>}>
{ items }
</InfiniteScroll>
);
}
}
const mapStateToProps = (state) => {
return {
timestamp: state.timestampReducer,
posts: state.postsReducer
}
};
export default connect(mapStateToProps)(Feed);
I used redux to manage the state of my posts. Next I added gem 'kaminari' to my gem file and ran bundle installed then added this line to my controller's index action: #posts = Post.all.order(created_at: :desc).page params[:page] and this to my model: paginates_per 5.
Now it scrolls and loads as expected! Awesome.
The solution would be to use pagination.
Every request will be bring only a set of records you'll specify in the method.
you can perform using gems like will_paginate, kaminari & this is the new gem called as pagy and they claim that it's faster than the other two.
Just increment the page parameter in the url after every request till the last page and you'll get the output you need.
I'm glad my opinion helped you :)
Change your JS code to this:
axios.post('/posts.json', {
params: {
page: page
}
}).then((response) => {
console.log(response.data);
...
}).catch(error => console.log(error));
}
Take a look at console.log(response) after axios then method so you can see the array of objects returning from the server. After then you can set it with .length property of method like:
axios.get('/posts.json')
.then((response) => {
if(response.data.length > 20){
console.log(response.data.slice(0,20))
}
})
.catch(error => console.log(error));

Open pdf in default app using pdfmake

I am able to create pdf in my ionic app and if I run the app in chrome it opens perfectly. However if I install my app on the android device it doesn't open. Below is my code. Can someone please help me if I have to do something extra to open it on device. I want to open it with default pdf application on device.
pdfMake.createPdf(dd).open();
Ok. After banging my head on wall for 3 days I finally found the solution and sharing here so that other people who are facing this issue can get help. I am creating pdf and saving it using cordova file plugin. After successful save I am opening it in default application using cordova file opener plugin. Below is my code.
pdfMake.createPdf(YOUR_DEFINITION_HERE).getBlob(buffer => {
this.file.resolveDirectoryUrl(this.file.externalRootDirectory)
.then(dirEntry => {
this.file.getFile(dirEntry, 'test1.pdf', { create: true })
.then(fileEntry => {
fileEntry.createWriter(writer => {
writer.onwrite = () => {
this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
.then(res => { })
.catch(err => {
const alert = this.alertCtrl.create({ message:
err.message, buttons: ['Ok'] });
alert.present();
});
}
writer.write(buffer);
})
})
.catch(err => {
const alert = this.alertCtrl.create({ message: err, buttons: ['Ok'] });
alert.present();
});
})
.catch(err => {
const alert = this.alertCtrl.create({ message: err, buttons: ['Ok']
});
alert.present();
});
});

React Native NetInfo always returns offline

I'm currently trying to implement some functionality in my react native app where I use information stored locally if the device is offline, and perform a fetch if the device is online.
I used NetInfo after reading this How to handle network failure in React-Native, when network is off, but unfortunately I ran into an error where NetInfo always returns offline. I found this github issue, which recommended that I change the host in RCTReachability.m from 'htpp://apple.com' to 'apple.com'. However, I couldn't find a file with that name in the project directory. Instead I found the only mention of 'apple.com' in any file, which was in RCTNetInfo.m, which was in the correct form.
Does anybody know a way to fix this problem? Or possibly a different way to go about performing one action if the device is online, and another if the device is offline?
Here's the relevant code:
fetchData() {
NetInfo.isConnected.fetch().done((isConnected) => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
if ( isConnected )
{
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
store.save('contacts', responseData.feed.entry)
.then(() => store.get('contacts'))
.then((contacts) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
})
})
.catch((error) => { console.error(error); });
}
else
{
store.get('contacts')
.then(contacts => {
if (contacts == null)
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(CONTACT_DATA),
isLoading: false
});
}
else
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
}
})
}
});
}

React Native IOS App crashes when no network conection

On the simulator it does not crash and Alerts the error, but in production it is crashes as soon as fetch request suppose to be made and it is impossible to reopen the app until network connection is back (I turn on/off airplane mode for the testing)
here are the snippets of my code
componentWillMount: function(){
NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
NetInfo.isConnected.fetch().done((data) => {
this.setState({
isConnected: data
})
console.log('this.state.isConnected: ', this.state.isConnected);
})
},
handleConnectivityChange: function(){
var connected = this.state.isConnected ? false : true
this.setState({isConnected: connected})
console.log('this.state.isConnected11: ', this.state.isConnected);
},
....
goToList: function(replace, listview){
console.log('this.state.isConnected: ', this.props.isConnected);
if (!this.props.isConnected){
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
return
}
....
fetch(url)
.then((response) => response.json())
.then((responseData) => {
....
.catch((error) => {
StatusBarIOS.setNetworkActivityIndicatorVisible(false)
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
})
.done()
I spent a lot of time trying to find a way to catch exceptions when using fetch() but I was unable to get it working (e.g. using .catch() or a try/catch blog didn't work). What did work was to use XMLHttpRequest with a try/catch blog instead of fetch(). Here's an example I based off of: https://facebook.github.io/react-native/docs/network.html#using-other-networking-libraries
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
var responseJson = JSON.parse(request.responseText);
// *use responseJson here*
} else {
console.warn('error');
}
};
try {
request.open('GET', 'https://www.example.org/api/something');
request.send();
} catch (error) {
console.error(error);
}

Resources