Design comparison
Solution retrospective
I am proud of the ability to create a more complex yet still intuitive and easy to use application that moves between and keeps track of many different states.
What challenges did you encounter, and how did you overcome them?Managing a large and more complex state by using useReducer to have all the state logic in one place and useContext to prevent excessive prop-drilling.
What specific areas of your project would you like help with?How to use Typescript properly to implement type-checking (especially for the context).
Community feedback
- @markuslewinPosted 6 months ago
Looks great! I think the type of the context value is meant to be
IPledgeDataProvider
, since you want to senddispatch
through the context.You can get rid of the type assertions in the context functions by setting the type of the context to
IPledgeDataProvider | undefined
, and switching the default value toundefined
. Your hook already narrows the type toIPledgeDataProvider
for consumers, so no further changes needed there!const PledgeDataContext = createContext<IPledgeDataProvider | undefined>( undefined ); function PledgeDataProvider({ children }: { children: React.ReactNode }) { // ... return ( <PledgeDataContext.Provider value={ // No assertion { // ... } } > {children} </PledgeDataContext.Provider> ); } function usePledgeData() { const context = useContext(PledgeDataContext); if (context === undefined) throw new Error( "PledgeDataContext was used outside of the PledgeDataProvider" ); // No assertion return context; }
Marked as helpful1@josh76543210Posted 6 months ago@markuslewin thank you very much for this feedback!
I have implemented the changes. So if I understand correctly the
IPledgeDataProvider
used when creating the context allows me to remove theIPledgeDataProvider
type assertions in the PledgeDataProvider and usePledgeData functions?1@markuslewinPosted 6 months ago@josh76543210 Precisely. Earlier, you had to assert the type to force the compiler to acknowledge the
dispatch
function on the object, but with the correct type forcreateContext
, the compiler can infer those types on its own0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord