Khirthan
Khirthan

Reputation: 197

React context value with typescript, not able to get the useState

export const EmployeeContext = createContext<EmployeesList[] | null>(null);

export const EmployeeProvider = ({ children }) => {
    const [employeeList, setEmployeeList] = useState<EmployeesList[] | null>(null);

    useEffect(() => {
        async function fetchData() {
            const results = await fetchEmployeeList();
            setEmployeeList(results);
        }
        fetchData()
    }, []);

    return (
        <EmployeeContext.Provider value={[employeeList, setEmployeeList]}>
            {children}
        </EmployeeContext.Provider>
    );
}

Both employeeList and setEmployeeList is throwing an error as "Type 'EmployeesList[]' is missing the following properties from type 'EmployeesList': userId, jobTitleName, firstName, lastName, and 5 more" Even though i have set or as null statement, and i have tried with default object also, still same error enter image description here

Upvotes: 1

Views: 320

Answers (1)

smac89
smac89

Reputation: 43206

This may have been a typo, but your return should be:

return (
    <EmployeeContext.Provider value={employeeList}>
        {children}
    </EmployeeContext.Provider>
);

If you want to also pass the setEmployeeList function, then change your context to the following:

type MutableEmployeesList = readonly [EmployeesList[], (employees: EmployeesList[]) => void];
export const EmployeeContext = createContext<MutableEmployeesList>(null);

Now the return should be:

const mutableEmployeesList = React.useMemo(() => [employeeList, setEmployeeList] as const, [employeeList, setEmployeeList]);

return (
    <EmployeeContext.Provider value={mutableEmployeesList}>
        {children}
    </EmployeeContext.Provider>
);

Upvotes: 1

Related Questions