• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

useAuthContext 에서 dispatch 를 사용할 때 에러가 나요.

23.04.24 00:11 작성 조회수 577

0

 

 

  const { dispatch } = useAuthContext();

 

위와 같이 사용했을 때 dispatch 아래에 밑줄이 생기는데

 

'null' 형식에 'dispatch' 속성이 없습니다.ts(2339)

const dispatch: any

 

와 같은 에러가 생깁니다.

(alias) const AuthContext: Context<null>
import AuthContext

 

이렇기 때문인 것 같은데 어떻게 수정해야할까요..

타입스크립트를 사용하고 있습니다.

답변 1

답변을 작성해보세요.

1

깨구리님의 프로필

깨구리

2023.04.28


Contextdispatch에 타입을 잘 넣어주시면 됩니다 :)
찾으신것처럼 Context에 타입을 null로 주셔서 아무것도 없는데 dispatch를 꺼내쓰려고 해서 생긴 오류입니다.

참고할만한 예제 코드를 드리겠습니다. 연습해보시고 적용하시면 좋을듯 해요. 화이팅입니다!

import { Dispatch, createContext, useContext,  useReducer } from 'react';


type Action = { type: 'increment' } | { type: 'decrement' };

function counterReducer(state: number, action: Action): number {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    default:
      throw new Error('Unhandled action type');
  }
}

const initialState = 0;

type CounterContextType = {
  state: number;
  dispatch: Dispatch<Action>;
};

const CounterContext = createContext<CounterContextType>({
  state: initialState,
  dispatch: () => {},
});

function CounterProvider(props: { children }) {
  const [state, dispatch] = useReducer(counterReducer, initialState);

  const value = { state, dispatch };

  return <CounterContext.Provider value={value} {...props} />;
}

function useCounterContext(){
  const context = useContext(CounterContext);
  return context
}


function Counter() {
  const {state, dispatch} = useCounterContext();
  const handleIncrement = () => dispatch({ type: 'increment' });
  const handleDecrement = () => dispatch({ type: 'decrement' });

  return (
    <>
      <h1>{state}</h1>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
    </>
  );
}

function App() {
  return (
    <CounterProvider>
      <Counter />
    </CounterProvider>
  );
}

export default App;