deadcoder0904
deadcoder0904

Reputation: 8683

How to use a React Hook `useWindowSize` to initialize window size inside a MobX Store?

I have win() function inside FrameItStore which returns window.innerWidth & window.innerHeight. But it doesn't always update when window size changes.

FrameItStore.ts

import { makeObservable, observable, action, computed } from 'mobx'

export class FrameItStore implements IFrameItStore {
  constructor() {
    makeObservable(this, {
      win: observable,
    })
  }

  win(): Window {
    return {
      width: window.innerWidth,
      height: window.innerHeight,
    }
  }
}

export const config = new FrameItStore()

So I want to use Window Size Hook → https://www.npmjs.com/package/@react-hook/window-size to get updated dimensions.

Problem is I don't know how to initialize the win() function with the hook value as hooks can only be called in React Component?

How do I do it?

Upvotes: 1

Views: 1150

Answers (1)

Tholle
Tholle

Reputation: 112777

Since you are storing the window dimensions outside of your React components, you could update them outside of the React components as well if you would prefer.

Example

import { makeObservable, observable, action } from 'mobx';

export class FrameItStore implements IFrameItStore {
  win = {
    width: window.innerWidth,
    height: window.innerHeight
  };

  constructor() {
    makeObservable(this, {
      win: observable,
      updateWin: action.bound
    });
    
    // Update this.win every time the window resizes
    window.addEventListener("resize", this.updateWin);
  }

  updateWin() {
    this.win.width = window.innerWidth;
    this.win.height = window.innerHeight;
  }
  
  // If your FrameItStore won't live for the entire duration of the application,
  // you can call this method to remove the event listener.
  destroy() {
    window.removeEventListener("resize", this.updateWin);
  }
}

Upvotes: 2

Related Questions