Here's where I'm triggering the Pusher event.
@app.route('/post-question', methods=['POST'])
def add_question():
data_received = json.loads(request.data)
data = {
'id':'post-{}'.format(uuid.uuid4().hex),
'title':data_received['title'],
'question':data_received['content'],
'status': 'active',
'event_name': 'created'
}
pusher.trigger("CHANNEL", 'question-created', data)
return jsonify(data)
Here's the Pusher channel binding:
<script>
function appendToList(data) {
const html = `
<div id="${data.id}">
<header>
<h1>${data.title}</h1>
</header>
<div>
<p>${data.question}</p>
</div>
</div> `
let list = document.querySelector('#post-list')
list.innerHTML = html
}
$(document).ready(() => {
$(document).on('click', "#submit", function(event) {
$.post({
url: '/post-question',
type: 'POST',
contentType: 'application/json;charset=UTF-8',
dataType: 'JSON',
data: JSON.stringify({'title': $("#question-title").val(), 'content': $("#question-content").val()}),
success : function(response) {
console.log(response);
},
error : function(xhr) {
console.log(xhr);
}
}).done(function(response) {
$("#question-form").reset()
})
})
})
Pusher.logToConsole = true;
const pusher = new Pusher('*', {
cluster: '*',
encrypted: true
});
const channel = pusher.subscribe('CHANNEL')
channel.bind('question-created', data => {
appendToList(data);
})
</script>
It correctly triggers the event, and appears correctly in another window in real time, but for some reason, when I reload the page, all the posts disappear; and the post disappears on the current window as well.
I think it might be a problem with the way I am rendering the posts, but I don't know. Anybody know how to fix this?
Thanks in advance!
CodePudding user response:
First comment is correct. Pusher takes care of real-time communication and new events. For showing old/existing posts every time page (re)loads, you need to query and render them in your app. You can choose to do that server-side or client-side.