Json being displayed instead on Vue component when browser's back <- button is clicked

Viewed 1052

I have created a small project using Laravel 5.4 and VueJs 2.0. It is not a Single Page Application. I am using vue components on each and every page to display the contents. The flow of my application goes like this: Whenever a use clicks on the tab in navbar, he's redirected to the respective component. On the laravel side, I am simply using return view(login); and on the login.blade.php, I am using <login-component></login-component> which then sends the ajax requests to fetch data. I don't really know if this is the right approach to get the 2 http requests generated (if anyone knows a better approach, please do let me know). Mostly for the ajax requests to load the vue component, the controller returns json data. Everything works fine, but when I click the back <- button on the browser, only json gets displayed. I then have to refresh the page (ctl + R) in the browser the get the vue component.

Here's the controller code:

public function index(Request $request, VideoRepository $video_repo, Channel $channel) {

    if ($request->ajax()) {
        $videos = $video_repo->getChannelVideos($channel);

        return response()->json([
            'data' => [
                'message'=> 'Success',
                'videos' => $videos,
                'channel' => $channel,
            ]
        ], 200);
    }

    return view('channels.index')->with([
        'channel_slug' => $channel->slug,
    ]);
}

Here's my channel.index page:

@extends('templates.default')

@section('content')
    <channel-dashboard channel-slug="{{ $channel_slug }}"></channel-dashboard>
@endsection

Here's my channel-dashboard vue component:

axios.get('/channels/' + this.channelSlug)
     .then(({data}) => {
        this.videos = data.data.videos;
        this.channel = data.data.channel;

        this.divideVideosArrayInChuncks();
     })
     .catch(({response}) => {
        this.error = response.data;
     });

Where am I going wrong??

1 Answers

If Laravel is using the same URL to show your Vue component AND to get the JSON to feed the component the browser may cache the JSON version and display it when you hit the back buttom. That could be the problem.

So you have to make sure both URLs are different maybe using a query param (like ?ajax=1) to know whenever you're serving JSON or not.

Here Craig Buckler wrote more about this problem: https://www.sitepoint.com/solve-caching-conundrums/

I hope this helps someone later!

Related