why can't Edit data display data that has been retrieved from an array (local storage) - arrays

running app- data array has been retrieved successfully, but cannot appear in the EditComponent section
edit(item: any) {
debugger
this._dialog.open(EditComponent)
this.guru = item;
}

Related

Problems passing sveltekit data to the frontend

I recently started learning Sveltekit and i adapted a small CRUD application that i made with express and PostgreSQL but i am not able to pass correctly the database data to the frontend. This is the code i wrote so far:
var query_output = undefined;
export const load = () => {
return {query_output}
};
export const actions = {
default: async (event) => {
let form_input = await event.request.formData();
let query = {
text: "select * from ux_return_shipments($1, $2, $3, $4)",
values: [form_input.get('beg-dep-date') || null, form_input.get('end-dep-date') || null, form_input.get('beg-arr-date') || null, form_input.get('end-arr-date') || null]
}
event.locals.pool.query(query)
.then(result => {
query_output = result.rows;})
}
};
The problem is that the data sent to the frontend is not the same extracted from the database. I suspect that this is caused by the fact that the second export requires time while the first one is performed immediately, therefore the 'query_output' variable sent to the frontend is always late.
How can i sync the two steps? Currently i am using two different exports because the second one reads the data that the user inserted in a form and also contains the db connection data through the locals attribute.
How can i sync the two steps?
You don't. load is for loading page data without any user input, form actions are for responding to form submissions from user interactions. They are completely separate and do not share state.
The action should return its own data which is passed to the page component as the form property. Data from load is passed to the data property.

How to save a list locally to a database with shared preferences in flutter?

How can I save a list locally to a database with shared preferences in flutter .
for example :- I have list List notification = []; How can I save this list locally with shared preferences?
The plugin itself already has a method for storing List<String>, it's called setStringList.
If you have some other type of data to store, you simply have to convert them in String and have a function to convert them back in your data type.
The other question linked in the comments is just a collection of convenience methods to store different data types, but it's nothing you can't write on your own.
const _notificationListKey='notificationList';
Future<void> notificationInLocalStorage( List notificationList ) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await Future.wait([
prefs.setString(_notificationListKey,json.encode( notificationList)),
]);
}

Fetch document only once when Firestore has updated

I have a tableView that bring all documents from Firestore collection and i want to fetch the last document only once when it is added to the Firestore after user refresh the tableView and after that I want to remove the listener so when the user refresh the tableView it only fetch document once , i used detach listener [from the documentation here][1] but it didn't work
func updatedFireStoredata() {
let listener = Firestore.firestore().collection("collection1").order(by: "date").limit(toLast: 1).addSnapshotListener() { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
let data = diff.document.data()
self.amount.append(data["amount"] as? String ?? "")
print("New city: \(diff.document.data())")
}
}
}
table2.reloadData()
listener.remove()
}
If your goal is to only call once to retrieve this document, I would consider using the offline persistence that is built in to the SDK. You will need to request the document once with offline persistence enabled, but after that call you can request this data from that local cache.
https://firebase.google.com/docs/firestore/manage-data/enable-offline
https://firebase.google.com/docs/firestore/manage-data/enable-offline#disable_and_enable_network_access
Alternatively you could store the document locally, and not include it in reload.
If it is the case that this data does change, just not as often as every refresh, it may make sense to move this to an eventing model. You can use firestore watch/listen to monitor that query and get update callbacks as needed. https://firebase.google.com/docs/firestore/query-data/listen
There are a couple of things
First, requiring a user to keep clicking refresh to get the current data is not a good experience. The data should be presented to the user automatically without interaction
Second, Firebase is asynchronous - code outside the Firebase closure will execute before the data in the closure. See my answer Firebase is asynchronous <- that's for the Realtime Database but the concept applies to asynchronous functions in general.
To fix both issues here's updated code
func updatedFireStoredata() {
let listener = Firestore.firestore().collection("collection1").order(by: "date").limit(toLast: 1).addSnapshotListener() { querySnapshot, error in
if let err = error {
print("Error fetching snapshots: \(err.localizedDescription)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
let data = diff.document.data()
self.amount.append(data["amount"] as? String ?? "")
print("New city: \(diff.document.data())")
}
}
table2.reloadData() //needs to be inside the closure
}
}
I moved the tableView reload inside the closure so it executes when new data arrives and then removed the code to remove the listener so your tableView will update with new data.
I also updated the error handler to handle an actual error code.
One thing you will want to do is to keep track of what the user has selected is is looking at - you don't want a selected item, for example, to un-select if other data is added which is what will happen when the tableView reloads.

React native fetch... Explain it like I'm 5

export default class App extends Component {
state = {
data: []
};
fetchData = async () => {
const response = await fetch("https://randomuser.me/api?results=5"); // Replace this with the API call to the JSON results of what you need for your app.
const json = await response.json();
this.setState({ data: json.results }); // for the randomuser json result, the format says the data is inside results section of the json.
};
So, I have this code in my App.js file for React Native. The randomuser.me is a website that just gives you random users. Using it as a test URL right now. I don't really understand what the code is doing enough to be able to use it for other parts of my project. I was able to successfully display the 5 user results but now I want to access them again and iterate through the data attribute of the state.
tldr; Can I just access the data I got from the fetch in a for loop using data[i]? Please advise. I want to see if user input matches any of the items in the response that is stored in data attribute of state.
Ok the thign that you just did, that is fetch. You retrieve data from the internet.
"https://randomuser.me/api?results=5" is an API, there is lot of different API's, and each one has it´s own way to retrieve data from. if you put "https://randomuser.me/api?results=5" in your browser, you are gonna see a JSON, some API's store data in JSON, others in an array format.
In this case, the JSON, has just one child, 'results', thats why you store "json.results".
That´s fetch. The thing that you want to do is just javascript.
Store json.results in a variable
then iterate over it
var Results = json.results //store it in a variable
for(var i = 0;i<Object.keys(Results).length;i++){ //iterate
var CurrentUser = Results[Object.keys(Results)[i]] // i use this because some JSOn have random keys
if(CurrentUser.gender==='male'){//if you meet a condition
//do whatever you want
}
}
you can also use ".map" if it´s an array

$scope not updating after passing to new view with $location.path

I have a simple CRUD I put together with Angularjs. From a product list display I pass the user to a new view template for the "Create New" form.
The form processes fine and updates the database. I then pass the user back to the list display using "$location.path(url)".
For some reason when the list page displays, the changes do not appear in the $scope and you have to refresh the page to see the changes.
Sample code:
$scope.acns = acnFactory.query()
.$promise.then(function (data) {
$scope.acns = data;
});
the above displays the list of items.
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
The above POSTs the new product then redirects to the list page (/acn)
My assumption is that the list page will reprocess or watch the changes to the $scope but the view does not update.
The problem is most probably here:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
creating a product most certainly consists in sending an HTTP request to the server. This is asynchronous. This means that acnFactory.create() returns immediately after the request has been sent. Not after the response has been received.
So, this code sends the request to create the product and immediately goes to the page which lists the products. The GET request sent to get the product list is thus sent almost at the same instant as the one used to create the new product. The two requests are handled concurrently by the server, and the returned list contains the list without the new product, which is being created in a separate transaction.
You need to wait for the response to come back, and make sure it's successful, before going to the product list. Assuming the service returns a promise, as it should do:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn).then(function() {
$location.path('/acn');
});
};

Resources