Next. js 14 With Mobx #3805
-
i tried to create state management with the next.js 14 app router with mobx but some how its not working its changing stats in store but not reflect on UI i also added observer but still not working in there any way to solve it ? and i created context to share the store globally. Please share if anyone integrates Mobx in Next. js With app router |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 7 replies
-
I fount solution for this this is how i implement 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; |
Beta Was this translation helpful? Give feedback.
-
How to initialize uiStore ?I can not find you initialize it anywhere |
Beta Was this translation helpful? Give feedback.
-
Thank you so much for your response. My project still isn't meeting expectations. Could you please take a look? I would greatly appreciate it. |
Beta Was this translation helpful? Give feedback.
-
Do you understand that your code will work only on client? |
Beta Was this translation helpful? Give feedback.
-
Not only will it only work on the client, it still needs SSR. |
Beta Was this translation helpful? Give feedback.
I fount solution for this this is how i implement mobx with next.js 14
store
group all store
provider
main layout