Update DOM in Realtime using Next.js 13


I have this issue on my Next.js app where I have two segregated components:

    <RouteList initialRoutes={initialRoutes} />
    <AddRouteComponent />

I would like for these components to share state so when a Route is added it shows immediately, this is for better user interaction as well as for better testing.

Looking at the above component due to the fact that it is a server component and rendered as such on the server we would have to go back and forth from the server and communicate with it from the server.

We could just combine the two client components as their logic is closely related.

I’ve yet to find a good solution for keeping the components above as such and sharing client side interaction thru the server, so lets combine them.

We are going to pass in a function as a prop for AddRouteComponent:

       <AddRouteComponent onRouteAdded={handleAddRoute} />

Then change AddRouteComponent to:

interface AddRouteComponentProps {
  onRouteAdded: (newRoute: Routes) => void;
}

export const AddRouteComponent = ({ onRouteAdded }: AddRouteComponentProps) => {

Next step, if network call successfull add onto the the list

Although this doesn’t check if the network call was successful it does add onto the list:

  const addRoute = async (newRoute: Routes) => {
    console.log();
    try {
      const routeToAdd = {
        ...newRoute,
        id: '', // This will be generated by the server
        routeNiceName: newRoute.routeNiceName,
        organizationID: orgId, // Use the orgId prop
        dateRouteAcquired:
          newRoute.dateRouteAcquired?.toISOString() || new Date().toISOString(),
        dateAddedToCB: new Date().toISOString(),
        assocTrucks: newRoute.assocTrucks || '',
        currentTruckForRoute: newRoute.currentTruckForRoute || '',
        allocatedShifts: newRoute.allocatedShifts || null,
        img: newRoute.img || '',
      };

      const response = await fetch('/api/add-new-route', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(routeToAdd),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // This is wrong, it should update
      const addedRoute = await response.json();
      console.log('Route added successfully', addedRoute);
      // This updates the route list in realtime. 
      handleRouteAdd(formData);
      // Sets the form entries the user added back to empty.
      setFormData(initialFormData);
      setShifts([]);
      return 'Route has been added successfully';
    } catch (error) {
      console.error('Error adding route:', error);
      throw error; // Re-throw the error so it can be handled by the caller if needed
    }
  };

For the above, it adds a route entry with relevant information.

The API file is as such: https://gist.github.com/MonteLogic/5526a0f51fe273b0faeae87623579eaf


Leave a Reply