2

I have a turbo frame as follows:

<turbo-frame id="details">
    Select a movie for more details...
</turbo-frame>

This frame is properly replaced when the a tag in the following is clicked, because the route /movie/show/1 returns a turbo frame with an id of "details"

<turbo-frame class="movie-cards" id="index">
    <a class="movie-card" data-turbo-frame="details" href="/movie/show/1">
        <div class="movie-item-detail text-center">
          LOTR
        </div>
    </a>
</turbo-frame>

However, running fetch("/movie/show/1") in the console returns the same turbo-frame response but doesn't replace anything. Why is this? Is there a way in general to cause a javascript-initiated request to update a turbo frame?

Jeffrey Maxwell
  • 304
  • 3
  • 7
  • 1
    "Turbo Streams consciously restricts you to seven actions: append, prepend, (insert) before, (insert) after, replace, update, and remove. If you want to trigger additional behavior when these actions are carried out, you should attach behavior using Stimulus controllers. This restriction allows Turbo Streams to focus on the essential task of delivering HTML over the wire, leaving additional logic to live in dedicated JavaScript files." – max Mar 20 '22 at 16:19

2 Answers2

0

There's a couple ways you can do this. You can either update the src attribute on the turbo frame itself, bypassing the need for fetch. Any time this attribute changes turbo will perform a get request to the URL and replace the given turbo frame provided with the response:

<turbo-frame id="index" src="/movie/show/1">

Or if you are using turbo streams you can use the response to fire off turbo to properly update the page (reference):

fetch(url, { headers: { Accept: "text/vnd.turbo-stream.html" } })
  .then(r => r.text())
  .then(html => Turbo.renderStreamMessage(html))
Leepoff
  • 134
  • 2
  • 6
0

Another way to achieve this without using turbo streams :

document.querySelector('turbo-frame[id="modal"]').src = modalUrl
Kevin
  • 65
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 15 '23 at 08:37