sendボタンを押すとメッセージは非同期で表示され、データベースにも残るが
リロードしないともう一度メッセージは送れず、
リロードするとメッセージデータが消える
検証ツールを使ったら以下のエラーが見受けられました
Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
at Subscription.received (message_channel.js:16)
at action_cable.js:536
at Array.map (<anonymous>)
at Subscriptions.notify (action_cable.js:535)
at Connection.message (action_cable.js:369)
actioncable使ってます
message_channel.js
ここの messages.insertAdjacentHTML('afterbegin', html);
部分でエラー
import consumer from "./consumer" consumer.subscriptions.create("MessageChannel", { connected() { // Called when the subscription is ready for use on the server }, disconnected() { // Called when the subscription has been terminated by the server }, received(data) { const html = `<p>${data.js_content.text}</p>`; const messages = document.getElementById('messages'); const newMessage = document.getElementById('message_text'); messages.insertAdjacentHTML('afterbegin', html); newMessage.value=''; // Called when there's incoming data on the websocket for this channel } });
messages controller
class MessagesController < ApplicationController def new @book = Book.find(params[:book_id]) @messages = Message.all @message = Message.new end def create @book = Book.find(params[:book_id]) @message = @book.build_message(message_params) if @message.save! ActionCable.server.broadcast 'message_channel', js_content: @message # redirect_to "/books/#{@book.id}/messages/new" end end private def message_params params.require(:message).permit(:text).merge(user_id: current_user.id) end end
メッセージのやり取りを行う場所 message new.html.erb
h1 class = "top-messsage"><%="#{@book.name}"%></h1> <% @messages.reverse_each do |message| %> <div class = "message-head"> <div id='messages'> <i><%= message.text %></i> <%= message.user.nickname%> </div> <% end %> </div> <div class="box-new"> <%= form_with model: @message, url: book_messages_path,local: true do |f| %> <%= f.text_field :text, id: "message_text" %> <%= f.submit '送信' %> <% end %> <div class="message-new"> <i class="container2"> <%= link_to 'home', "/", class: "btn-open3" %></i> </div> </div>
`
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。