Create higher order function for composing and using useReducer into another components gives me an error

381 Views Asked by At

I want to create a higher order function which contains useReducer hook as a singleton in order to composite with other components. But i got an error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

My HOF:

const initialState = {
  status: ''
};

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'SHOW':
      return {
        ...state
      }
    default:
      return state;
  }
}

const WithReducer = WrappedComponent => (props) => {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <>
      <WrappedComponent {...props}/>
    </>
  )
}

export default WithReducer;

And a try to compose:

connect(mapStateToProps, mapDispatchToProps)(WithReducer(App));

Where did i go wrong ?

1

There are 1 best solutions below

0
On

got an answer to myself

 const WithReducer = WrappedComponent => {
      const Reducer = (props) => {
        const [state, dispatch] = useReducer(reducer, initialState);
        return (
          <>
            <div>{state.status}</div>
            <WrappedComponent {...props} state={state} dispatch={dispatch}/>
          </>
        )
      }
      return Reducer;
    }