Typescript complains that my setReposlist is undefined. I am confused because I think have previously typed using this interface:
export interface ReposContextInterface {
reposList: {},
setReposList?: Dispatch<SetStateAction<reposList>>
}
export interface SearchPageContextInterface{
searchRepos: ReposContextInterface
}
export const SearchPageContext = createContext({} as SearchPageContextInterface);
and I define the context on my app.tsx:
<SearchPageContext.Provider value={{searchRepos: {reposList, setReposList}}}>
but when I use the context on my react component like this:
const SearchPage = useContext(SearchPageContext);
const {searchRepos} = SearchPage;
useEffect(()=>{
const getRepos = async (username: string) =>{
const repos = await axios.get(`https://endpoint/${username}/repos`);
if(repos) {
const {data} = repos;
const temp:any = {};
temp[username] = data;
setReposList({...reposList, ...temp});
} else {
setReposList({...reposList});
}
};
getRepos(username);
},[]);
it gives me this error message: Cannot invoke an object which is possibly 'undefined'.ts(2722) const setReposList: React.Dispatch<React.SetStateAction> | undefined
Please help. Thank you.
I would suggest entirely removing the optionality in the context type and using a dummy object as an initial value. Something like this:
If you wish to keep the optionality of the
setReposList, you can use optional chaining: