4

I have a button that calls handleApplyFiltersButtonClick which updates the state by applying filters to some data. I have a bug somewhere. I'm struggling to debug the state which uses Immers' produce as everything is either a proxy or function. I would rather not use Immer but that's the teams' choice.

From the docs it seems a producer function usually takes the current state and a function with the parameter draft passed to wehre state changes are made and recorded... not doing that here though.

How can I view the updated state? As console.log('nextState', nextState) leads to just a function with no info.

handleApplyFiltersButtonClick = () => {
    const nextState =  produce((state) => {
        state.page = 1;
        state.appliedFilters = { ...state.filters };
        state.filteredHealthProviders = this.getFilteredHealthProviders(state.healthProviders, state.appliedFilters)
    })
    console.log('nextState', nextState)
    this.setState(
       nextState,
    );
};
Nick Lee
  • 842
  • 2
  • 11
  • 27

1 Answers1

2

When you pass a function as the first argument of produce, a producer is created, which is a function that creates a draft of whatever value you pass to it and passes that draft to your produce callback.

If you care about the return value, you need to wrap the producer with a function that you pass to setState.

handleApplyFiltersButtonClick = () => {
  const producer = produce((state) => {
    state.page = 1;
    state.appliedFilters = { ...state.filters };
    state.filteredHealthProviders = this.getFilteredHealthProviders(state.healthProviders, state.appliedFilters);
  })
  this.setState(
    state => {
      const nextState = producer(state);
      console.log('nextState', nextState);
    },
  );
};
aleclarson
  • 18,087
  • 14
  • 64
  • 91