0

I am using MobX in a Next.js app. The problem is in the StoreProvider component. I follow the instruction on this website. The problem is

[mobx] The provided value could not be converted into an observable. If you want just create an observable reference to the object use 'observable.box(value)

This is the RootStore

// import { firestore } from 'firebase';
import CandidatesStore from './CandidateStore';
import AuthStore from './AuthStore';
// import 'firebase/firestore';

class RootStore {
  candidateStore: CandidatesStore;

  authStore: AuthStore;

  constructor() {
    this.candidateStore = new CandidatesStore(this);
    this.authStore = new AuthStore();
  }

  init(): void {
    this.candidateStore.fetchCandidate();
  }
}

export default RootStore;

This is the StoreProvider that the console told that the problem come from here.

import * as firebase from 'firebase';
import 'firebase/firestore';
import React from 'react';
import { useLocalStore } from 'mobx-react';
import firebaseConfig from '../constants/firebase.config';
import RootStore from '../core/mobx/RootStore';

const storeContext = React.createContext(null);

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const StoreProvider = ({ children }) => {
  const store = useLocalStore(() => new RootStore());
  return <storeContext.Provider value={store}>{children}</storeContext.Provider>;
};

export default StoreProvider;

export const useStore = (): RootStore => {
  const store = React.useContext(storeContext);
  if (!store) {
    throw new Error('useStore must be used within a StoreProvider');
  }
  return store;
};

This is the CandidateStore that could be the source of problem.

class CandidatesStore {
  rootStore: RootStore;

  @observable candidates: Array<Candidate>;

  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
  }

1 Answers1

1

The concept is Mobx cannot observe any value since it will never change, to give an example if you do

@observable(3) // 3 will never change, so mobx throws error
// and in case we have such requirement, we either can put 3 in some variable and observe
that variable or do 

const x = observable.box(3) 

//then we can look for changes and make changes with 
x.set(4)
autorun(() => console.log(x))

why are you facing this error, may be because candidates is initialized to undefined

Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73