I'm integrating a mock API which basically send a response object with a set of messages that are supposed be shown in the UI(Chatbox) along with Username, user pic and so on.
I'm having some trouble setting up the msw 1.1.0
with Next JS 13.2.1
(Experimental app directory with layouts) because of the breaking changes. However this is my code.
My code is set up like this so far
src/app/(user)/live-view/page.tsx
import React from "react";
import ThreadPostList from "../../components/threadList";
import { worker } from '../../../mocks/browser';
if (process.env.NODE_ENV === 'development') {
worker.start();
}
async function getMessages() {
const response = await fetch("http://localhost:3000/api/messages");
// const data = await response.json();
return response;
}
async function LiveViewPage() {
const messages = await getMessages();
const convertedMessages = Object.keys(messages);
// console.log(convertedMessages, "ConvertedMessages");
Object.values(messages).forEach(val => console.log(val));
return (
<div className="border-t border-gray-200 py-4 divide-y divede-gray-200">
<ThreadPostList />
</div>
);
}
export default LiveViewPage;
And my Msw mock API is under
src/mocks/handler.ts
import { rest } from "msw";
import { UserWithMessages } from "./types";
const mockData: UserWithMessages[] = [
{
user: {
id: "user1",
name: "John Doe",
profilePic: "https://example.com/user1.jpg",
},
messages: [
{
id: "msg1",
senderId: "user1",
text: "Hey, how are you?",
createdAt: new Date("2022-01-01T12:00:00Z"),
},
{
id: "msg2",
senderId: "user1",
text: "Did you get my email?",
createdAt: new Date("2022-01-02T12:00:00Z"),
},
],
},
{
user: {
id: "admin",
name: "Admin",
profilePic: "https://example.com/admin.jpg",
},
messages: [],
},
];
export const handlers = [
rest.get<UserWithMessages[]>("/api/messages", (req, res, ctx) => {
return res(ctx.status(200), ctx.json(mockData));
}),
];
And finnaly my browser.ts is under
src/mocks/browser.ts
"use client"
import { setupWorker } from 'msw';
import { handlers } from './handlers';
export const worker = setupWorker(...handlers);
when I run the server it's throwing an error
Error: Cannot access worker.start on the server. You cannot dot into a client module from a server component. You can only pass the imported name through.
Where and How do I start my worker? Do I have to create a file under mocks and call the server there and import that component in my page.tsx?Any help would be appreciated thanks