Home > Blockchain >  Type 'Dispatch<any>' is not assignable to type '() => null'.ts(2322)
Type 'Dispatch<any>' is not assignable to type '() => null'.ts(2322)

Time:05-18

I was creating my context for my application and I have this typescript error 'Type 'Dispatch' is not assignable to type '() => null'.ts(2322)', I am something new with typescript and I don't understand the error.

this is my code:

import { createContext, useEffect, useReducer } from "react";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  loading: false,
  error: null,
  dispatch: ()=>null
};

export const AuthContext = createContext(INITIAL_STATE);

const AuthReducer = (state:any, action:any) => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        user: null,
        loading: true,
        error: false,
      };
    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        loading: false,
        error: false,
      };
    case "LOGIN_FAILURE":
      return {
        user: null,
        loading: false,
        error: action.playload,
      };
    case "LOGOUT":
      return {
        user: null,
        loading: false,
        error: null,
      };
    default:
      return state;
  }
};

export const UserContextProvider = ({ children }:any) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);


  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        loading: state.loading,
        error: state.error,
        dispatch, //error
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

the error marks me when I want to pass Dispatch in the value of my context.

CodePudding user response:

You can fix that error by importing and using the Dispatch type from React:

import {
  // ...
  type Dispatch,
} from 'react';

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  loading: false,
  error: null,
  // Use a type assertion on the line below, like this:
  dispatch: (() => undefined) as Dispatch<any>,
};

// ...

You can see that the type of the value of dispatch that you get from useContext is that type. Here's a modified version of the code that you posted in your question with the changes above in the TypeScript playground.

  • Related