Firestore updateDoc by id - javascript

I want update informations getting doc by id but I receive erros my code.
Idk how solve this sorry about my english. I just want to update the information I think is a basic error, but I can't solve it sorry
I receive Expected type 'Ta', but it was: a custom Aa object
const updateFields = (e) => {
e.preventDefault()
updateDoc(TopStoryAnswersCollectionRef, {
response_B6: responseB6,
response_B9: responseB9,
response_B12: responseB12,
response_B15: responseB15,
response_B18: responseB18,
response_B21: responseB21,
response_B24: responseB24,
response_B27: responseB27,
response_B28: responseB28,
response_B29: responseB29,
response_B32: responseB32,
response_B33: responseB33,
response_B34: responseB34,
response_B35: responseB35,
response_B38: responseB38,
user_uid: currentUser.uid,
}).then(() => {
alert('Updated')
})
setFormSubmitted(true)
}

Your variable TopStoryAnswersCollectionRef should be a reference to a document when using updateDoc not a reference to a collection. See sample code below:
const updateFields = (e) => {
e.preventDefault()
const TopStoryAnswersCollectionRef = doc(db, "collection-name", "document-id");
updateDoc(TopStoryAnswersCollectionRef, {
response_B6: responseB6,
response_B9: responseB9,
response_B12: responseB12,
response_B15: responseB15,
response_B18: responseB18,
response_B21: responseB21,
response_B24: responseB24,
response_B27: responseB27,
response_B28: responseB28,
response_B29: responseB29,
response_B32: responseB32,
response_B33: responseB33,
response_B34: responseB34,
response_B35: responseB35,
response_B38: responseB38,
user_uid: currentUser.uid,
}).then(() => {
alert('Updated')
})
setFormSubmitted(true)
You could also incorporate a query using where() if you still don't have the document reference to update to.
For more information, you may checkout this documentation.

Related

webshare API multiple instances on same page

Hopefuly someone can assist/direct me here.
I'm making use of the webshare API on my site. The site contains an array of posts that will have a share link. This is built using a foreach and all have unique urls to use. I want to add a share button to each of those images. I currently have it working on a singular instance but unable to get it to loop through all the share buttons.
Here is the current script:
const shareButton = document.querySelector('.share-button');
const url = document.querySelector('.post-link a').href;
shareButton.addEventListener('click', event => {
if (navigator.share) {
navigator.share({
title: 'Check out this ad I saw on ...',
url
}).then(() => {
console.log('Shared');
})
.catch(console.error);
}
});
I'm really struggling with how to get it to loop through all share buttons and not just be usable on the first instance.
Apologeis if this is simple.
For a start, you need to add a click listener to all buttons, not just the first. You can do this exclusively when the API is supported, else, you may want to hide the buttons. Here's the modified script (note that you need to get the URL of each post individually, see the comment):
const shareButtons = document.querySelectorAll('.share-button');
if ('share' in navigator) {
shareButtons.forEach((shareButton) => {
shareButton.addEventListener('click', () => {
// Get the URL from the dataset or query the DOM.
const url = shareButton.dataset(url);
navigator.share({
title: 'Check out this ad I saw on ...',
url
}).then(() => {
console.log('Shared');
}).catch(console.error);
});
});
} else {
shareButtons.forEach((shareButton) => {
shareButton.style.display = 'none';
});
}

RxJS: Observable.webSocket() get access to onopen, onclose…

const ws = Observable.webSocket('ws://…');
ws.subscribe(
message => console.log(message),
error => console.log(error),
() => {},
);
I want to observe my WebSocket connection with RxJS. Reacting to onmessage events by subscribing to the observable works like a charm. But how can I access the onopen event of the WebSocket? And is it possible to trigger the WebSocket .close() method? RxJS is pretty new to me and I did research for hours, but maybe I just don't know the right terms. Thanks in advance.
Looking at the sourcecode of the Websocket there is a config object WebSocketSubjectConfig which contains observables which you can link to different events. You should be able to pass a NextObserver typed object to config value openObserver like so:
const openEvents = new Subject<Event>();
const ws = Observable.webSocket({
url: 'ws://…',
openObserver: openEvents
});
openEvents
.do(evt => console.log('got open event: ' + evt))
.merge(ws.do(msg => console.log('got message: ' + msg))
.subscribe();
The link of #Mark van Straten to the file is dead. The updated link is here. I also wanted to highlight the usage as suggested in the docs. A in my opinion better copy and paste solution to play around with:
import { webSocket } from "rxjs/webSocket";
webSocket({
url: "wss://echo.websocket.org",
openObserver: {
next: () => {
console.log("connection ok");
},
},
closeObserver: {
next(closeEvent) {
// ...
}
},
}).subscribe();

Axios PUT Request in React, Redux Not Working

So I want to make a PUT request to the server, but it doesn't want to work. I know that when making a PUT request you need an identifier(e.g id) for the resource and the payload to update with. So that is my problem.
In my form I have these props:
<div>
<DoorSettingsForm
onSubmit={this.submit.bind(this)}
item={this.props.location.state.item}
id={this.props.location.state.item._id}
/>
</div>
item - All the input fields, radiobuttons etc.
id - The identifier
onSubmit - the function that handles the submitting of all of the new data, here it is:
submit(values, id) {
this.props.updateSettings(values, id)
}
And inside of my really simple action I have this:
export function updateSettings(id, item) {
return dispatch => {
console.log('ID: ', id)
return axios
.put(`${settings.hostname}/locks/${id}`, item)
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
One thing that I really don't understand is when I change the places of id and item on the first line the output of my console.log changes. When having id as the first parameter I get everything I've typed in my inputs (the changes) and when having item as the first parameter I'm getting this:
ID: function (action) {
if (action.payload) {
if (!(0, _isPromise2.default)(action.payload) && !(0, _isPromise2.default)(action.payload.promise)) {
return next(action);
}
Any help with my problem is really appriciated! Thanks for reading.
I forgot to call handleSubmit with my id:
form onSubmit={() => handleSubmit(id, item)}

Use sequelize query results inside a jquery event handler

There is an electron framework that gives you a stripped down browser to build your user interface for the desktop application. In my case, I am using jQuery for DOM navigation, Sequelize to talk to my sqlite database and a couple other libraries.
Let's say I have a text field where the user can type a movie name. My database stores a couple hundred movie names. So I would like to offer the user autocomplete suggestions.
Typically, I would use something like this to register a jQuery handler (this will echo field input back to console):
$('#movie-search-field').on('input', (event) => {
console.log(event.target.val())
})
With sequelize, you would typically have a model (say, Movie) and query it like so: Movie.findAll(). Here comes the problem:
If I register my handler like so:
Movie.findAll().then((movies) => {
$('#movie-search-field').on('input', (event) => {
/*Use movies here to build and show a suggestions list*/
})
})
then it never gets triggered. I have verified that the .then clause is entered by printing movies to console from within it.
On the other hand, if I try to query the database from inside the handler:
$('#movie-search-field').on('input', (event) => {
Movies.findAll().then((movies) => {
/*Use movies to build and show a suggestions list*/
})
})
then the handler exits before the promise is resolved and no suggestions are shown.
How could I use the database query results in my event handler?
You could just make a simple callback
$('#movie-search-field').on('input', (event) => {
getResults(function(movies) {
/* Display your movies */
})
})
function getResults(callback) {
Movies.findAll().then((movies) => {
/*Use movies to build and show a suggestions list*/
callback(movies)
})
}
So when a user types in the input box it will request the suggestions and then when it returns them it will call the function (callback) and then you can display them
Turns out I made some unrelated mistakes in my event handler code and so the approach I described above works just fine:
Movie.findAll().then((movies) => {
$('#movie-search-field').on('input', (event) => {
/*Use movies here to build and show a suggestions list*/
})
})
Also, if you are doing several database queries and would like your handler to have access to all of those, you can do:
let movies = Movie.findAll()
let tickets = Ticket.findAll()
Promise.all([movies, tickets]).then(values => {
let [movies, tickets] = values
/* register your handlers here and pass the data to them */
$("#some-selector").on('input', {movies: movies, tickets: tickets}, (event) => {
let movies = event.data.movies
let tickets = event.data.tickets
/* some event handling code that uses both movies and tickets */
})
})

AngularFire2 Firebase update object without causing other subscriptions to update

I just have a question to find out if this is possible:
So what I am doing is when I submit a post I wait for it to complete then update the user object in firebase to insert a time-stamp.
This is fine and works but when the time-stamp is inserted it is causing other subscriptions that are subscribed to changes in the user object to update.
What I want to do it update the user object without causing other subscribers to be updated.
Here is where I am updating the timestamp:
I tried commenting out this line of code which stops the data duplication issue on screen but I need this code to run as I need to update the timestamp when a post is submitted.
this.af.database.object('users/' + x[0].uid + '/lastPostAt').set(timestamp)
.then(x => { this.dialogsService.showSuccessDialog('Post Submitted'); });
Here is where I am subscribing to all the posts:
subscribeAllPosts(): Observable<Post[]> {
return this.af.database.list('/posts')
.map(Post.fromJsonList);
}
Here is where I am creating the array of posts in my constructor to display via a loop in the html:
this.activeItem = this.items[0];
this.postsService.subscribeAllPosts()
.subscribe(posts => {
let container = new Array<PostContainer>();
for (let post of posts) {
this.getEquippedItemsForUsername(post.username).subscribe(
x => {
try {
container.push(new PostContainer(post, x[0].equippedItems));
} catch (ex) { }
}
);
}
this.postContainers = container;
});
In the inner subscription it gets the equippedItems for the user of the post:
getEquippedItemsForUsername(username: string) {
return this.usersService.subscribeUserByUsername(username);
}
Which in turns calls:
subscribeUserByUsername (username: string) {
return this.af.database.list('users' , {
query: {
orderByChild: 'username',
equalTo: username
}
});
}
In the HTML it loops through the postContainer[]:
<li *ngFor="let item of postContainers">
So all that works the issue as stated is that if I do not have the following commented out then the posts will be duplicated more and more as the posts are submitted. If I refresh the app then the posts will show the correct non duplicated posts until another post is submitted.
this.af.database.object('users/' + x[0].uid + '/lastPostAt').set(timestamp)
.then(x => { this.dialogsService.showSuccessDialog('Post Submitted'); });
EDIT: Solved by splitting up logic.

Categories

Resources