简体   繁体   中英

How to call a Function which is called inside Reducer, and the said Function uses the State returned by useReducer?

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 aCodeSandBox 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM