2

Currently, when changing states in a component, I subscribe the state to a store which updates when a function I call finishes. I do this by:

useAirQualityStore.getState().updateAirQuality();

...

this.state = useAirQualityStore.subscribe(state => this.setState(state));

However, when I am working on a screen where I need to use multiple stores, I have more parameters and can't set the entire state. Could I subscribe certain parameters of my state to listen for changes in the stores?

My idea of this would be somehow passing in the previous state but it seems a bit messy:

useWeatherStore.subscribe(console.log, state => this.setState(prevState => {
      return {
        ...prevState,
        forecast: state.dailyForecast,
        weatherIsLoading: state.forecast.isLoading
      }
    }));

Is there a better way to do this?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
ThrillHaus
  • 71
  • 1
  • 8

1 Answers1

-1

Turns out in Zustand, you can subscribe a components state to more than one store. The values and parameters are just appended to the same state. For example,

this.state = useWeatherStore.subscribe(state => this.setState(state));
this.state = useAirQualityStore.subscribe(state => this.setState(state));

This will append the data from 'useWeatherStore' and 'useAirQualityStore' to 'this.state'. It appears to update accordingly.

ThrillHaus
  • 71
  • 1
  • 8
  • Upon further investigation, this is more intricate than thought. I currently use a wrapper around my returns and use the 'shallow' package in Zustand to subscribe to certain parts of each store. – ThrillHaus Jan 23 '22 at 17:33