My issue here most likely happens since I am not instantiating the mock server in the correct place in my app. The mirageJs docs are still catered to the old 'pages router', where it says:
Open your Next.js app's initialization file (pages/_app.js), import your makeServer function, and call it in the development environment...
The problem is that I am not aware of such initialization file. I tried doing it in the Root Layout but it failed.
here is my server code:
import { createServer, Model } from "miragejs"
export function makeServer({ environment = "test" } = {}) {
let server = createServer({
environment,
models: {
movie: Model,
},
seeds(server) {
server.create("movie", { name: "Inception", year: 2010 })
server.create("movie", { name: "Interstellar", year: 2014 })
server.create("movie", { name: "Dunkirk", year: 2017 })
},
routes() {
this.namespace = "api"
this.get("/movies", (schema) => {
return schema.movies.all()
})
},
})
return server
}
and here is my component making the request:
'use client'
import {React, useState, useEffect} from "react"
export default function Assets(){
const [assets, setAssets] = useState([])
useEffect(() => {
fetch("/api/movies")
.then((res) => res.json())
.then((json) => {
setAssets(json.movies)
})
}, [])
// get assets from miragejs server
// map and display them here
const assetElements = assets.map(asset => {
<div>
<p>{asset.name}</p>
<p>{asset.year}</p>
</div>
})
return (
<>
{assetElements}
</>
)
}
I tried creating the server within the same file as the component calling it and it works - but I want to centralize my server so I can reuse it everywhere in my app.
Would appreciate any help here, thanks!
Hi I faced the similar issue and finally got it working, as you mentioned it need the client component to work, else its is throwing error. something similar what there document also showing. https://miragejs.com/docs/getting-started/introduction/
in project i also try using material tailwind , https://www.material-tailwind.com/docs/react/guide/next, so on top level i have this file where i importing and exporting material tailwind component.(like Theme Provider which is part of my app, layout file) on same i called my custom function start Mock Server as well that have code to createServer for miragejs. and then it working for other route as well like /shop.