MobX not hydrating in next.js state when fetching async data

Viewed 177

I have a MobX store where I have a function doing an API call. It works fine it's getting the data but it doesn't update the already rendered page. I'm following this tutorial https://medium.com/@borisdedejski/next-js-mobx-and-typescript-boilerplate-for-beginners-9e28ac190f7d

My store looks like this

const isServer = typeof window === "undefined";
enableStaticRendering(isServer);

interface SerializedStore  {
    PageTitle: string;
    content: string;
    isOpen: boolean;
    companiesDto: CompanyDto[],
    companyCats: string[]
};

export class AwardStore {
    PageTitle: string = 'Client Experience Awards';
    companiesDto : CompanyDto[] = [];
    companyCats: string[] = [];
    loadingInitial: boolean = true
    constructor() {
        makeAutoObservable(this)
    }


    hydrate(serializedStore: SerializedStore) {
        this.PageTitle = serializedStore.PageTitle != null ? serializedStore.PageTitle : "Client Experience Awards";
        this.companyCats = serializedStore.companyCats != null ? serializedStore.companyCats : [];
        this.companiesDto = serializedStore.companiesDto != null ? serializedStore.companiesDto : [];
    }

    changeTitle = (newTitle: string) => {
        this.PageTitle = newTitle;
    }

    loadCompanies = async () => {
        this.setLoadingInitial(true);
        axios.get<CompanyDto[]>('MyAPICall')
            .then((response) => {
                runInAction(() => {
                    this.companiesDto = response.data.sort((a, b) => a.name.localeCompare(b.name));
                    response.data.map((company : CompanyDto) => {
                        if (company.categories !== null ) {
                            company.categories?.forEach(cat => {    
                                this.addNewCateogry(cat)
                            })
                        }
                    })
                    console.log(this.companyCats);
                    this.setLoadingInitial(false);
                })
            })
            .catch(errors => {
                this.setLoadingInitial(false);
                console.log('There was an error getting the data: ' + errors);
            })
    }

    addNewCateogry = (cat : string) => {
        this.companyCats.push(cat);
    }

    setLoadingInitial = (state: boolean) => {
        this.loadingInitial = state;
    }
}

export async function fetchInitialStoreState() {
    // You can do anything to fetch initial store state
    return {};
}

I'm trying to call the loadcompanies from the _app.js file. It calls it and I can see in the console.log the companies etc but the state doesn't update and I don't get to see the actual result. Here's the _app.js

class MyApp extends App {


constructor(props) {
    super(props);
    // Don't call this.setState() here!
    this.state = {
        awardStore: new AwardStore()
    };
    this.state.awardStore.loadCompanies();
  }

// Fetching serialized(JSON) store state
static async getInitialProps(appContext) {
    const appProps = await App.getInitialProps(appContext);
    const initialStoreState = await fetchInitialStoreState();

    return {
        ...appProps,
        initialStoreState
    };
}

// Hydrate serialized state to store
static getDerivedStateFromProps(props, state) {
    state.awardStore.hydrate(props.initialStoreState);
    return state;
}

render() {
    const { Component, pageProps } = this.props;
    return (
        <Provider awardStore={this.state.awardStore}>
            <Component {...pageProps} />
        </Provider>
    );
}
}
export default MyApp;

In the console.log I can see that this.companyCat is update but nothing is changed in the browser. Any ideas how I can do this? Thank you!

2 Answers

When you do SSR you can't load data through the constructor of the store because:

  1. It's does not handle async stuff, so you can't really wait until the data is loaded
  2. Store is created both on the server side and on the client too, so if theoretically constructor could work with async then it still would not make sense to do it here because it would load data twice, and with SSR you generally want to avoid this kind of situations, you want to load data once and reuse data, that was fetched on the server, on the client.

With Next.js the flow is quite simple:

  1. On the server you load all the data that is needed, in your case it's loaded on the App level, but maybe in the future you might want to have loader for each page to load data more granularly. Overall it does not change the flow though
  2. Once the data is loaded (through getInitialProps method or any other Next.js data fetching methods), you hydrate your stores and render the application on the server side and send html to the client, that's SSR
  3. On the client the app is initialized again, though this time you don't want to load the data, but use the data which server already fetched and used. This data is provided through props to your page component (or in this case App component). So you grab the data and just hydrate the store (in this case it's done with getDerivedStateFromProps).

Based on that, everything you want to fetch should happen inside getInitialProps. And you already have fetchInitialStoreState method for that, so all you need to do is remove data fetching from store constructor and move it to fetchInitialStoreState and only return the data from it. This data will then go to the hydrate method of your store.

I've made a quick reproduction of your code here:

Edit https://stackoverflow.com/questions/72978402

The huge downside if App.getInitialProps is that it runs on every page navigation, which is probably not what you want to do. I've added console.log("api call") and you can see in the console that it is logged every time you navigate to any other page, so the api will be called every time too, but you already have the data so it's kinda useless. So I recommend in the future to use more granular way of loading data, for example with Next.js getServerSideProps function instead (docs).

But the general flow won't change much anyway!

Calling awardStore.loadCompanies in the constructor of MyApp is problematic because the loadCompanies method is populating the store class. What you want is to hydrate the store with the companyCats data. Since server and client stores are distinct, you want to load the data you need on the server side i.e. fetchInitialStoreState (or load it from a page's getStaticProps/getServerSideProps method) so that you can pass it into the hydrate store method from page/app props.

Note loadCompanies is async so it'll be [] when getDerivedStateFromProps is called so there's nothing to hydrate. For your existing hydrate method to work you need initialStoreState to be something like the fetchInitialStoreState method below. Alternatively if it's fetched on the page level, the hydrate may be closer to initialData?.pageProps?.companyCats

It's common to see the store hydration as needed for each page though it's still valid to call loadCompanies() from the client side. There's a lot I didn't get a chance to touch on but hopefully this was somewhat helpful.

export const fetchInitialStoreState = async() => {
  let companyCats = [];
  try {
    const response = await axios.get < CompanyDto[] > ('MyAPICall')

    response.data.map((company: CompanyDto) => {
      if (Array.isArray(company.categories) && company.categories.length > 0) {
        companyCats.push(...company.categories)
      }
    })
  } catch (error) {
    // Uh oh...
  }

  return {
    serializedStore: {
      companyCats,
      // PageTitle/etc
    }

  }
}

Related