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!