Home > OS >  How to call a Function which is called inside Reducer, and the said Function uses the State returned
How to call a Function which is called inside Reducer, and the said Function uses the State returned

Time:09-06

React v17
I am using useReducer. In the reducer function, I need to call another function check for network fetch. In check( ), I need to access the state, which is returned by useReducer.
I am getting this error can't access lexical declaration 'value' before initialization.

const reducerFilterdValue = (state, action) => {
    let newState ;
    switch(action.type){
      case 'increment':
        if(check()===0){
          newState={...state,counter:state.counter 1}
        }        
      break;
      default:
        newState={...state}
      break;
    }    
    return newState;
    }

const check=()=>{
   return state.counter%2
}

const [state, dispatchValue] = useReducer(
  reducerFilterdValue,
  initialFilterdValue
) 

I have made a CodeSandBox for explanation purpose.

What is the efficient way to restructure the code?

A. Should I need to call check from outside the useReducer? To do that, I think I will need to use useEffect.

B. I declared check outside of the functional component as a let variable, and defined it after reducer function, but it was not working correctly and state was getting changed more than once.

C. Some better approach which I am unable to find out?

CodePudding user response:

The reducer should be responsible for merging/reducing state and that is all.

As someone in your question comments said, there should not be any side effectw in reducer (only state manipulations). So change the state in the reducer and check the counter state by using useEffect and dependency variables.

  • Related