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?