I have a simple react application and I am able to add data to it, but I am not sure how to remove/update data.
the main problem is in getting the part where I tell firebase which data to remove. how do I tell that to firebase.
I am using react.
I have been trying out different things but it's just not working
handleRemove(){
console.log('you reached handleRemove function');
var ref =firebase.database().ref('items');
ref.on('value',this.handlegetData,this.handleErrData);
['items']['KpAmo20xP6HPXc7cwjY'].remove();
//itemsRef.remove('KpAmo20xP6HPXc7cwjY');
}
Please tell me how to do this.
My firebase database looks somewhat like this
You need something like that to remove value :
handleRemove() {
return firebase.database().ref('items').child('ITEM_KEY').remove();
}
or something like that to update value :
handleUpdate() {
var updates = {};
updates['/id'] = 1;
updates['/title'] = 'Apple';
return firebase.database().ref('items').child('ITEM_KEY').update(updates);
}
(In your screenshot items is equal to firebase-test)
Here the Firebase Realtime Database documentation.
Related
I'm developing an app using React Native that allows you to create your own checklists and add items to them.
For example you'd have "Create Checklist", and inside that you'll have the option to "Add Item", "Delete Item" "Edit Item", basic CRUD methods etc.
It's going to be completely offline but I'm wondering what the best approach to storing this data locally would be.
Should I be using a DB such as firebase? I have read that it is overkill and to use something like Redux but I'm not sure if the latter will accomplish everything I need. As long as it's storing data which can be edited, and will save on the user's device (with minimal effort) it sounds good to me.
Would appreciate some input on this, thanks!
You could use AsyncStorage for persisting data locally on the user's phone. It is a simple persistent key-value-storage.
Each checklist is most likely an array of JS objects. The documentation provides an example on how to store objects.
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('#storage_Key', jsonValue)
} catch (e) {
// saving error
}
}
The value parameter is any JS object. We use JSON.stringify to create a JSON string. We use AsyncStorage.setItem in order to persist the data. The string #storage_Key is the key for the object. This could be any string.
We retrieve a persisted object as follows.
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('#storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch(e) {
// error reading value
}
}
Both examples are taken from the official documentation.
Keep in mind that this functionality should be used for persistence only. If the application is running, you should load the complete list, or parts of the list if it is very large, in some sort of application cache. The implementation for this functionality now heavily depends on how your current code looks like. If you have a plain view, then you could access the local storage in an effect and just store it in a local state.
function MySuperList() {
const [list, setList] = useState([]);
React.useEffect(() => {
// retrieve data using the above functionality and set the state
}, [])
// render list
return (...)
}
I would implement some sort of save button for this list. If it is pressed, then we persist the data in the local storage of the phone.
I am currently writing a ReactJS UI for my c# Project. It will run in a CEFSharp control.
Now I try to save the state of a Reacj object whenever the state is changed.
When the c# programm is (re-)started the saved state should be restored in the page.
What is working so far:
Transmitting the state and saving it in c# is working:
exportState(){
if(navigator.userAgent === 'CEF')
{
let jsonstate = JSON.stringify(this.state.Fenster);
window.nativeHost.kontrolstate(jsonstate);
}
}
Fenster is an array of an own defined object.
To be able to push the saved state back to the react component I have created an ref:
<Kontrolle ref={(kont) => {window.Kontrolle = kont}} />
So I can call the procedures of component Kontrolle via a javascript call in CEFSharp.
To restore the state I call this procedure:
jsontostate(jsonstring){
var fen = jsonstring;
let fenster = this.state.Fenster;
for (var i=0; i<fen.length;i++) {
var f = fen[i];
let index = fenster.findIndex(x => x.id === f.id);
fenster[index].colum = f.colum;
fenster[index].offen = f.offen;
fenster[index].sort = f.sort;
}
this.setState({Fenster: fenster});
this.render();
}
It looks like working perfecly.
The state is updated correctly.
Also when I check the state in the debug console of CEFSharp it looks correctly.
There is also no error displayed in the console.
What is not working:
The state has influence to the page.
After calling the procedure the page is not rendered newly.
So the state and page are not in line.
I already have tried to force a render.
Without success.
Where is my mistake?
Can someone give me a hint?
Found the reason by myself.
I did implement the component Kontrolle twice.
One with ref one without ref.
I checked the rendered UI on the wrong implementation.
So, my own mistake.
The code I have posted work fine.
Thanks to all.
I have generated the api in sailsjs using
sails generate api testAPI
and I have been able to create data using the command
http://localhost:1337/testAPI/create?username=f1&password=123
and i can get the result
but when I want to customize the route
for get - http://localhost:1337/testAPI/1
i am using the code
module.exports = {
findOne:function(req,res){
res.ok('overridden');
}
};
in testAPIController.js for the overriding
and when I go the route http://localhost:1337/testAPI/1 I am able to see overriden displayed there.
but how do I query the data and show a customized view there?
to customize and query the data I am using this code and it doesnt work
says that testAPI not defined
module.exports = {
findOne:function(req,res){
var results = testAPI.find()
res.ok(results);
}
};
so, what am I doing wrong here?
The model you created should be used with the first capital letter (TestAPI.find());
Also, you should consider the assync factor when fetching data. See code bellow
module.exports = {
findOne:function(req,res){
TestAPI.find().then(function(results) {
return res.ok(results);
});
}
};
I'm using LokiJS to save in local storage (well, I'm trying) .
What I want to do is a ToDo app, my controller is as follows:
.controller('Dash', function($scope) {
var db = new loki('loki.json');
$scope.name="";
$scope.lname="";
var users=db.getCollection('users');
if (users==null) {
$scope.message="It's null";
var users = db.addCollection('users');
}else{
$scope.message="It's ready";
}
$scope.insert=function(namesI, lnameI){
users.insert({
name: namesI,
lname:lnameI
});
}
The issue is that everytime that I test it, the message is "It's null". Although before already I have inserted data. I mean, everytime I launch the app, the database is created.
How I can persist the data?
*I'm not using any cordova plugin.
You are not providing a loadHandler function, so you are trying to access collections before Loki is finished loading the json file. Look at this example for a clarification on how to use the autoLoadHandler.
Also bear in mind that at some stage you need to call db.saveDatabase() to persist, or else you need to provide an autoSaveInterval value when instantiating Loki.
I am trying to create a 'Favorites' section in my app where you hit a button and it is added to a user favorites list in firebase. I am using the ionic platform.
I created a factory to handle the favourites as they come in. and i use the getAuth() function to get the unique userID so i can just pull it when the user logs on. This is my attempt but i am not getting the result i wanted which is simply something like :
< userid >:
{
0: "fav1"
1: "fav2"
}
.factory('Favourites',function($firebaseArray){
var ref = new Firebase("https://experiencett.firebaseio.com/");
var authData = ref.getAuth();
var favs = $firebaseArray(new Firebase('https://experiencett.firebaseio.com/favourites/'+authData.uid+''));
return {
all: function() {
return favs;
},
add: function(){
var up=new Firebase('https://experiencett.firebaseio.com/favourites/');
var usersref=up.child(authData.uid);
usersref.push({3:"paria"});
},
When you call push() you are generating a unique id. While that is great for many use-cases, it is not good here since you want to control the path that is written.
Since you're already constructing the path with child(authData.uid) you can simply update it with update():
usersref.child(authData.uid).update({3: "paria"});
This will either update the existing value at 3 or write the new value for 3, leaving all other keys under /users/<uid> unmodified.
Alternatively if you want to replace the data that already exists at users/<users>, you can use set() instead of update().
This is all covered in the Firebase JavaScript SDK in the section on storing user data. It is not covered in the AngularFire documentation, since there is nothing specific to Angular about it.