Rails 7 and React monolith having routing errors when the page needs to be refreshed. How do I mitigate this?

15 Views Asked by At

Building a Rails 7 app using ESBuild and react in the same project.

The React Router: app/javascript/routes/index.js

import React from "react";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
import Folders from "../components/Folders";
import Folder from "../components/Folder";
import UploadView from "../components/UploadView";

const AppRoutes = () => (
  <Router>
    <div className="d-flex flex-column" style={{ minHeight: '100vh' }}>
      <Navbar />
      <div className="flex-grow-1">
        <Routes>
          <Route path="/" element={<Folders />} />
          <Route path="/folder/:id" element={<Folder />} />
          <Route path="/uploads/:uploadId" element={<UploadView />} />
        </Routes>
      </div>
      <Footer />
    </div>
  </Router>
);

export default AppRoutes;

Rails Routes: app/config/routes.rb

Rails.application.routes.draw do

  root "home#index"
  get "home/index"
  namespace :api do
    namespace :v1 do
      resources :folders, only: [:index, :create, :show, :destroy] do
        resources :uploads, only: [:index, :create, :show, :destroy, :update] do 
          resources :comments, only: [:index, :create, :update] do
            member do
              patch :soft_delete
            end
            resources :replies, only: [:index, :create, :update]
          end
        end
      end
    end
  end
  devise_for :users

  
  get "up" => "rails/health#show", as: :rails_health_check
end

The app works as expected with the data served correctly, but the route in the browser is served with the React url for the page, thus if the page is refreshed, it leads to a Rails:

Routing Error
No route matches [GET] "/folder/10"
Rails.root: /home/stephan/delivery_V2

Application Trace | Framework Trace | Full Trace

When setting the react routes equal to the rails routes on refresh, it will serve the JSON data returned by the controller instead of going to the react routes.

How can I fix this, a link to the Upload must be shared and viewed, commented on by multiple people at possibly the same time. therefor refreshing the page is inevitable. I do use react state management, I'm just sure that not being able to refresh a page is not commercially viable.

I have tried setting the react routes equal to the rails routes, but on refresh the data being served on screen is the API data instead of the React page

0

There are 0 best solutions below