In a react project, there is a globally available context for alert and messages. In any given component, I can use a context.setAlert() to put up a message.
I have some API fetching logic extracted into a utility function. It's not a component. Components import and use this function in various ways prior to render, sort of like this:
//MyComponent.js
import {fetchFromApi} from "../util"
import AlertContext from "../contexts/alert"
const MyComponent = () => {
const alertContext = useContext(AlertContext)
useEffect(() =>
fetchFromApi(...)
.then(() => alertContext.setAlert('All set'), [])
return <Something/>
}
So in fetchFromApi, I'd like to be able to use that AlertContext.setAlert method. Something like this:
// util.js
export const fetchFromApi = (params) =>
fetch("...")
.then(something)
.then(somethingelse)
.then(response => {
// set alert from the AlertContext is what I want to access
if (response.status === 500) alertContext.setAlert('oh no')
return response
})
I'm not sure if/how I can update a context state outside of a component. Is this possible?