DEV Community

Discussion on: React Context with useReducer and Typescript.

Collapse
 
infosec812 profile image
Deven Phillips

Finally! A Context/Reducer tutorial which uses typescript and DOESNT just show how to change the theme name... Any chance you would be willing to add a custom Dispatcher which could resolve promises from REST API Calls? All of our API calls return Promises, and the dispatch method in React cannot resolve Promises, so I would love to see an example of a "Dispatcher" which wraps the default dispatch function to handle resolving Promises!

Collapse
 
dipique profile image
Daniel Kaschel

It's not a best practice to include your API calls in your reducer. The purpose of your reducer is to accept incoming state changes and apply them to the context.

Instead, when an action occurs in a .tsx component, write code like this:

apiCallFunction(args).then(result => dispatch(Actions.ThisAction, result))

This will cause the context to be updated when the api call finishes, and then your reducer can apply the results, update the context, and React will handle updating the DOM.