thewei / react-native-store Goto Github PK
View Code? Open in Web Editor NEWA simple database base on react-native AsyncStorage.
Home Page: https://github.com/thewei/react-native-store
License: Other
A simple database base on react-native AsyncStorage.
Home Page: https://github.com/thewei/react-native-store
License: Other
can someone help me, how I can delete item?
When I try delete it, resp always is null.
import Store from 'react-native-store';
const DB = {
'users': Store.model('users')
}
DB.users.removeById(1).then(resp => {
console.log("Data Check: ", resp);
})
I noticed that the source was converted to what appears to be babel output with 2215361
Is there a reason for this? I'd like to contribute more, but I can't make sense of the code anymore. Should we be contributing on a dev branch and have master be babel output (for some reason)?
Hi there,
Great lib!
I can't make the remove
method work with a filter though.
this.model = await reactNativeStore.model("link");
// ...
await this.model.remove({
where: {
_id: id,
}
});
Since it is not in your test suite either, I can't make myself confortable it actually works.
Does anyone knows how to connect AsyncStorage with loopback.io?
What I am looking is to use loopback (browserify or etc) + connector for AsyncStorage in React Native app. Then set up auto sync with backend api. So app may work offline...
I was wondering if it gets deleted once the app is closed? Because then I feel like using sqlite is a better option.
Sorting works well for letters, however not for numbers.
Eg. I could have a list of: 1, 2, 12, 4, 24, 45
And it'll sort as follows: 1, 12, 2, 24, 4, 45
Perhaps I'm doing something incorrect? Love some feedback.
What do you think about adding a new function, or updating the existing UpdateById function to add it regardless of where it exists or not?
I'm working on an Enterprise app that must store 40000+ records, when the react-native-store db grows too large it becomes inaccessible because it cannot retrieve a key/value so massive and it throws this error:
Error: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
In the simulator I'm running this error occurs when the string value reaches about 2300000 characters, I'm not sure if there is workaround possible right now.
I started implementing my own Wrapper which divides each Collection into shards, when I got something working and stable I'll post it.
Thx for the lib anyways, it's very useful in every other way ๐
When I try to add things to my storage, it doesn't always add correctly, and many times just overwrites the last item, it doesn't give a new id, just keeps using the last one.
I was having this issue in another part of my app, where there was a race condition and the first call hadn't finished when the second one started, but that shouldn't be the case here, nor should that be an issue anyway. Storage should be able to handle items coming in rapid succession.
thoughts?
This library is great, and using it is good, as the React team did take the pain to say:
It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.
But I'd like to question the way it is implemented: on every write, the whole database is parsed, modified and stored again.
If the content grows, won't this have a great performance dropdown?
Shouldn't different entries be written in various key/values? And the table names could be prefixed.
The aim of this issue is simply to discuss this point. If at some point there actually is a need to change something, it shouldn't be too hard to rewrite since the API is very small (add
, update
, remove
, find
)
Hi, This is an awesome project and a great work on AsyncStorage. Appreciate it. Will surely contribute to this repo.
Here I have a example project that I have got up and running using this store.
Most of the code is the same as what's given in the Basic example.
'use strict';
var React = require('react-native');
var reactNativeStore = require('react-native-store');
var {
AsyncStorage,
PickerIOS,
Text,
AppRegistry,
View
} = React;
var test = async function() {
//Get/Create model
var userModel = await reactNativeStore.model("user");
// Add Data
var add_data = await userModel.add([{
username: "tom",
age: 12,
sex: "man"
},{
username: "test",
age: 22,
sex: "man"
},{
username: "1test",
age: 42,
sex: "man"
}]);
// return object or null
console.log("add_data "+JSON.stringify(add_data));
// Update Data
var update_data = await userModel.update({
username: "mary"
},{
where: {
username: "tom"
}
});
console.log("update_data "+JSON.stringify(update_data));
//Remove data with a filter
var remove_data = await userModel.remove({
where: {
age: { lt: 15 }
}
});
console.log(remove_data);
//Remove all data (pass no where filter)
var remove_data = await userModel.remove();
console.log("remove_data"+JSON.stringify(remove_data));
// search using advanced queries
var find_data = await userModel.find({
where: {
and: [{ username: { neq: 'tom' } }, { age: { gte: 40 } }]
},
order: {
age: 'ASC',
}
});
console.log("find ",JSON.stringify(find_data));
}
var AsyncStorageExample = React.createClass({
getInitialState() {
return test();
},
render : function() {
var color = this.state.selectedValue;
return (
<View>
<Text>Hello</Text>
</View>
);
},
});
AppRegistry.registerComponent('AsyncStorageExample', () => AsyncStorageExample);
When I run the code, I see that the data that gets printed in the console isn't right. Here is the output-
12-07 20:54:05.261 22955-10626/com.asyncstorageexample I/ReactNativeJS: add_data [{"username":"tom","age":12,"sex":"man"},{"username":"test","age":22,"sex":"man"},{"username":"1test","age":42,"sex":"man"}]
12-07 20:54:05.271 22955-10626/com.asyncstorageexample I/ReactNativeJS: update_data null
12-07 20:54:05.291 22955-10626/com.asyncstorageexample I/ReactNativeJS: null
12-07 20:54:05.306 22955-10626/com.asyncstorageexample I/ReactNativeJS: remove_data[[{"username":"tom","age":12,"sex":"man"},{"username":"test","age":22,"sex":"man"},{"username":"1test","age":42,"sex":"man"}]]
12-07 20:54:05.316 22955-10626/com.asyncstorageexample I/ReactNativeJS: 'find ', 'null'
Output that I expected-
What am I doing wrong? Isn't the expectation right?
Hi,
First of all I am pretty new to this javascript world, when there is an error API blowing up on my face with console errors , instead it should reject a promise with error object isn't it ?
The local cache can not remove when app reinstall, how to do?
Hope to change as a primary key model, query and more efficient operation of some.
Can be directly inserted data, otherwise we must first find, and then add or update.
It works after removing .babelrc.
Hello. By any chance do you happen to have any instructions to help with your new API. I was using 0.0.3, and am interested in upgrading to your latest version, but I am incredibly confused with the new API methods.
Thanks. -Albert
Hi,
In my app i am backing up client data on server while restoring i want to copy server data to client, is there any API to directly replace all rows of model, instead of remove all and then adding one by one!.
What is the best way to loop through stored data to display a list with each object? These will be anonymized JSON objects stored in the DB.
I have tried .map, but the response returns an array of length 1 instead of each individual element. Any suggestions?
Hi,
Here is my response data
[{
"confirmation": "Success",
"response": [{
"_id": "5a4f487089b4860014cddc51",
"img1": "https://windows-price.s3.amazonaws.com/windows/1517418755884american-craftsman-double-hung-windows-3254786-64_1000.png",
"name": "Double Hung (half-screen)",
"__v": 0,
"price": 900,
"updated": "2018-01-05T09:42:08.170Z",
"is_sash": false,
"sash": [],
"comments": "",
"oriel": "false",
"is_oriel": false,
"dimension_size": 0,
"is_speciality_selected": false,
"is_speciality": false,
"is_style": false,
"is_grids": false,
"styles": [],
"dimension": [],
"Tempered": "0",
"Obscure": "0",
"quantity": 0,
"with_grid_price": 725,
"with_out_grid_price": 675,
"grids": [],
"grid": "0",
"max_ui": 136,
"max_height": 84,
"max_width": 52,
"min_ui": 0,
"min_height": 25.25,
"min_width": 16
}, {
"_id": "5a4f491a89b4860014cddc52",
"img1": "https://windows-price.s3.amazonaws.com/windows/1520980539939dbl-hung-oriel.png",
"name": "Double Hung (Oriel Style) (half-screen)",
"__v": 0,
"price": 500,
"updated": "2018-01-05T09:44:58.772Z",
"is_sash": false,
"sash": [],
"comments": "top sash cannot exceed 50\"",
"oriel": "false",
"is_oriel": false,
"dimension_size": 0,
"is_speciality_selected": false,
"is_speciality": false,
"is_style": false,
"is_grids": false,
"styles": [],
"dimension": [],
"Tempered": "0",
"Obscure": "0",
"quantity": 0,
"with_grid_price": 0,
"with_out_grid_price": 0,
"grids": [],
"grid": "0",
"max_ui": 136,
"max_height": 84,
"max_width": 52,
"min_ui": 0,
"min_height": 25.25,
"min_width": 16
}
i want use it search for that i used the command db.user.findById({"_id":"5a4f487089b4860014cddc51"}) but it is returning the response as null.
can any one give be suggestions that how can i done this.
Any suggestions much appreciated
hi ~
sometimes data missing when i refresh js on simulator
can you explain why? how to store data permanently??
I actually just wanted to ask, how do you write tests for react-native components like AsyncStorage? I wrote a module recently that uses AsyncStorage, and I have tape tests for it, but I'm not sure how to set it up.
Hi, I want to keep the example code(with modifications) as a module. So, can I reference that module with parameters to refer to a store?
Giving an example, say RNStoreUtil is the utility module having all the functions defined by react-native-store (init, destroy, filter, etc etc.,)
And say I need a User Model, a Data Model & a History Model.
Can the init() function be something like-
async init(modelName, testDataSet) {
model = await reactNativeStore.model(modelName);
for(var element in testDataSet) {
await model.add(testDataSet[element]);
}
}
and from my react native module, can I do something like-
await this.init("user",arrayOfObjects1);
.
.
.
await this.init("data",arrayOfObjects2);
.
.
Similarly other functions^ as well..
Can I do something like this? I tried it, but, I am blocked due to some other issue. So, need some thoughts, so that I can at least finish coding while the other issue is being fixed.
I'm getting exceptions because of bugs in promise-es6
Unable to resolve module util from /project/mobile/node_modules/react-native-store/node_modules/promise-es6/lib/utils.js
Suggest you switch to es6-promise which looks like a more mature project
300 and 40 stars and not a single tutorial or Example
I am impressed with the popularity of react-native-store but unable to implement. Let me write a secnario
var storage = {
'following': Store.model('following'),
'token': Store.model('token')
}
storage.following.add({following: responseData})
storage.token.add({token: responseData.token})
storage.following.find().then(resp => console.log(resp));
storage.token.find().then(token => console.log(token));
whenever i try to fetch i am unable to get the required results. sometimes it returned null and sometime it returned only one from the two.
A load current page cache, avoid repeated rendering.
when I add more than 1 time, like:
DB.zamba.add({ id: "account", value: { username: username, password: password, isSaveAccount: true } }); DB.zamba.add({ id: "isSaveAccount", value: { isSave: true } });
It only saves "isSaveAccount". How can I fix this?
Hi,
I have big file JSON object (700 articles from Pocket's API) i'd like to add, but I experience some problems.
//Create/get model from storage
this.model = await reactNativeStore.model('articles');
//Add our test data to storage
for(var element in arr) {
await this.model.add(arr[element]);
//console.log("Item Added")
}
Is there a solution or workaround for this?
I'm getting null when I run find() against a new database. I'm wondering if this is correct?
In line with most db management systems, results should never return null but rather, in case there is no result, an empty array.
const DB = {
USERTABLE : Store.model("Users")
}
export function loadUser(userId){
return dispatch => {
return DB.USERTABLE.find()
.then(users => { //users is null
I put together http://reactnativemodules.com last night and added your module. It's a community run list of react native modules. Hopefully it will make finding projects like these easier. Am I missing any that you know of?
https://github.com/thewei/react-native-store/blob/master/libs/model.js#L172
result can be either null/array , return undefined if its null otherwise pop!
This is my code. When I call add() method, the data gets stored but it can be seen after I perform add() once again.
var React = require('react-native');
var {
StyleSheet,
View,
Text
} = React;
var Store = require('react-native-store');
var DB = {
foo: Store.model('foo')
};
module.exports = React.createClass({
getInitialState: function(){
return{
items: null,
string: ''
}
},
render: function(){
return(
<View style={styles.container}>
<Text onPress={this.onButtonPress}>Add Item</Text>
<Text onPress={this.destroyData}>Destroy</Text>
<Text>{this.state.string}</Text>
</View>
);
},
onButtonPress: function(){
DB.foo.add({
fname: 'Mihir',
lname: 'Karandikar'
});
DB.foo.find()
.then((response) => this.setState({ items: response, string: JSON.stringify(response) }));
console.log(this.state.items);
},
destroyData: function(){
DB.foo.destroy();
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#eaeaea',
alignItems: 'center',
justifyContent: 'center'
}
});
When I console.log this shows up:
adding item...
null
adding item...
null
adding item...
[Object]0: Object
length: 1
__proto__: Array[0]
Hi there -
I have followed the full document to save and retrieve data using this library.
But unfortunately not working for few devices - when the app force closed.
Here is my code -
Import:
import AsyncStorage from '@react-native-community/async-storage';
Retreiving Data -
`const getUserData = async () => {
try {
const user_id = await AsyncStorage.getItem("user_id");
const user_name = await AsyncStorage.getItem("user_name");
const user_email = await AsyncStorage.getItem("user_email");
const user_phone = await AsyncStorage.getItem("user_phone");
const user_address = await AsyncStorage.getItem("user_address");
console.log("User Data ============= " + user_name);
if(user_id !== null) {
setId(user_id);
setName(user_name);
setEmail(user_email);
setPhone(user_phone);
setAddress(user_address);
setLoading(false);
console.log("User Data Found. " + user_name);
}
} catch(e) {
console.log("User Data NOT Found. Error Occurred. Error - " + e);
}
}`
Saving data -
`const saveLoginInfo = async (id, name, email, phone, address, access_token) => {
try {
console.log("Data to save - " + id + ", " + name + ", " + email + ", acess token: " + access_token);
await AsyncStorage.setItem("user_id", id+"");
await AsyncStorage.setItem("user_name", name);
await AsyncStorage.setItem("user_email", email);
await AsyncStorage.setItem("user_phone", phone);
await AsyncStorage.setItem("user_address", address);
await AsyncStorage.setItem("access_token", access_token);
} catch (e) {
// saving error
console.log("Data Not SAVED - " + e);
}
}`
Is there any solution? Any help would be appreciated.
When I'm calling entities.get(id) I'm expecting to receive entity or null, empty array is confusing here, imho.
Any plans to implement a contains filter for property values?
Storage recommendations can use table instead of database, you can add table prefix, to avoid conflicts, but also facilitate unified delete. This can improve the efficiency, but also convenient to operate outside the library program.
npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements! npm ERR! peerinvalid Peer [email protected] wants react-native@>=0.5
currently find API returning only array of objects
find({ limit : 10}) // [1..10 objects]
it will be cool if it adds more meta info like
{ total : 100 ,rows : [1..10] }
Hi,
You've mentioned that the like filter isn't implemented, is it something on the roadmap?
Hi, I tried to use react-native-store
according the simple sample in README file. It seems the add
function is not working as you described in that sample.
I firstly created below user
model.
var reactNativeStore = require('react-native-store');
var DB = {
'user': new reactNativeStore.model('user'),
}
module.exports = DB;
Then I tried to add some item:
DB.user.add({
'accessToken': jsonRes.token,
}).then(resp => console.log('Added Item: ',resp));
I kept getting below issue:
Could you give me a hand on this issue? Do you know if the error is related to react-native-store
?
Thanks a lot!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.