Combine Original and Mocked Responses in MSW

Share this video with your friends

Send Tweet

When working with existing APIs, especially those you don't own, being able to take the original response and manipulate it can be a life-changer when iterating on features or reproducing bugs. In this lesson, you will learn to perform the original request and then use Mock Service Worker to patch it with whichever data you want.

~ 7 months ago

In case anyone is wondering why this isn't working in your course app, in "_grid._index.jsx" in the loader it is still calling the mock api instead of a production api.

I copied api.recommendations and renamed the copy to api.featured and then changed the fetch url in the loader. I'm running vite so my port is different.

export async function loader() {
  const featuredMovies = await fetch(
    // "https://api.example.com/movies/featured"
    "http://localhost:5173/api/featured"
  ).then<Array<FeaturedMovie>>((response) => response.json());

  return {
    featuredMovies,
  };
}
Artem Zakharchenko
Artem Zakharchenko(instructor)
~ 6 months ago

You're totally right! I believe I switched to the local /api/featured for this lesson only so it never made it to the repository.

Here's the code you have to adjust in _grid._index.tsx:

export async function loader({ request }: LoaderFunctionArgs) {
  const featuredMovies = await fetch(
-  'https://api.example.com/movies/featured',
+   new URL('/api/featured', request.headers.get('origin'))
  ).then<Array<FeaturedMovie>>((response) => response.json())

  return {
    featuredMovies,
  }
}

Refer to the Remix documentation on how to annotate the loader function arguments.

Thank you for pointing this out!