#Global Error Context typescript errors

2 messages · Page 1 of 1 (latest)

zenith birch
#

I'm working on converting my project to Typescript and working through all the typescript errors.

I have this error context provider:

import React, {
    useState,
    createContext,
    useContext,
    ReactNode
} from 'react';
import PropTypes from 'prop-types';

type ErrorContextType = {
    globalError: string;
};
const GlobalErrorContext = createContext<
    ErrorContextType | undefined
>(undefined);
type ErrorActionsContextType = {
    setGlobalError: (data: ErrorContextType) => void;
    // Add other authentication actions here
};
const GlobalErrorActionsContext = createContext<
    ErrorActionsContextType | undefined
>(undefined);

export const useGlobalErrorContext = () =>
    useContext(GlobalErrorContext);
export const useGlobalErrorActionsContext = () =>
    useContext(GlobalErrorActionsContext);

type ErrorProviderProps = {
    children: ReactNode;
};
const GlobalErrorContextProvider = (props: ErrorProviderProps) => {
    const { children } = props;
    const [globalError, setGlobalError] = useState('');

    return (
        <GlobalErrorContext.Provider value={globalError}>
            <GlobalErrorActionsContext.Provider value={setGlobalError}>
                {children}
            </GlobalErrorActionsContext.Provider>
        </GlobalErrorContext.Provider>
    );
};

GlobalErrorContextProvider.propTypes = {
    children: PropTypes.node.isRequired
};

export default GlobalErrorContextProvider;

And the two value keywords in the return statement are throwing errors. TS2322: Type  string  is not assignable to type  ErrorContextType  index.d.ts(371, 9): The expected type comes from property  value  which is declared here on type IntrinsicAttributes & ProviderProps<ErrorContextType | undefined

stuck ruin
#

Your context is created requiring ErrorContextType | undefined

const GlobalErrorContext = createContext<
    ErrorContextType | undefined
>(undefined);

But you are using a string type for globalError

const [globalError, setGlobalError] = useState('');