How do I integrate the Next.js 14 app router with Next.js? I have integrated the Next.js 14 app router with MobX, but the UI does not update when I update the store data. Before this, I was getting an 'undefined' error. To resolve this, I changed the function to an arrow function and it solved the problem. However, the UI is still not updating. I have also added the observer from the MobX-React package.
I figure it out how to integrate Mobx with Next.js 14
//store
export class UiStore {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment = () => {
this.count++;
};
}
//group all store
export const RootStore = {
uiStore,
};
//provider
"use client";
import React, { createContext, ReactNode } from "react";
import { RootStore } from "@/store/store";
export const StoreContext = createContext(RootStore);
export const StoreWrapper = ({ children }: { children: ReactNode }) => {
return (
<StoreContext.Provider value={RootStore}>{children}</StoreContext.Provider>
);
};
//main layout
<StoreWrapper>{children}</StoreWrapper>
//hook to get stores
import { useContext } from "react";
import { StoreContext } from "@/store/provider";
export const useStores = () => {
return useContext(StoreContext);
};
//component where you want to use store
"use client";
import { observer } from "mobx-react";
import { useStores } from "@/hooks/useStore";
const HomePage = observer(() => {
const {
uiStore: { count, increment },
} = useStores();
return (
<>
<div>{count}</div>
<button onClick={increment}>Increment</button>)
</>
);
});
export default HomePage;