Reputation: 129
I have a onReady
callback which fires whenever a global object is loaded from an external library. The object is only loaded when authentication is done.
There are pages that require authentication and there are some that are not, so i don't want to load it before loading the page.
I have therefore created a service which is not a component, which fires previously mentioned onReady
event, which should set the flag the the library has finished loading and I could do stuff with it. The solution that came to my mind is to set it globally in a redux store, and then whenever onReady
is fired I would set the state like this.
export const onReady = event => {
const dispatch = useDispatch();
dispatch(setReady());
}
Which results with following error:
×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
So I am wondering how can I set global redux state in a service function? Other solutions solving the problem would also be appreciated.
Upvotes: 0
Views: 316
Reputation: 2644
You can use dispatch
directly from Redux:
import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))
Example from: https://redux.js.org/api/store#dispatchaction.
Replace the store
with your own store.
Alternatively you can rename onReady
to useOnReady
, so React will mark it as a Hook.
Upvotes: 1