I am setting language for my app. But I have a problem.
I use React.useContext()
to set language. But when I fix it in saga's toast, it log:
[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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.]
So can I use it in saga? If yes, how should I use it? If no, can you suggest me a solution.
The final solution is props message from saga.
This is a function of my 'toast.js' file:
export function toastLoginSuccess() {
ToastAndroid.show(
LANGUAGES.toastLoginSuccess,
ToastAndroid.SHORT,
ToastAndroid.TOP,
);
}
with LANGUAGE is import * as LANGUAGES from '../asset/language';
and toastLoginSuccess
is export const toastLoginSuccess = 'Login success!';
I want change it to const LANGUAGES = React.useContext(LanguageContext).language;
And saga is a file similar to:
export function* fetchSigninSaga(action) {
try {
// ...
yield Toast.toastLoginSuccess())
} catch (error) {
// ...
yield Toast.toastLoginFail();
}
}
You need to inject your context in saga first, below is the way to achieve it,
import createSagaMiddleware from "redux-saga";
const userService = createUserService(...);
const sagaMiddleware = createSagaMiddleware({
context: LanguageContext
});
sagaMiddleware.run(rootSaga);
Once you have injected, you the use it in the below manner,
import { getContext } from "redux-saga/effects";
export function* loadUsersSagas(action) {
const languageContext = yield getContext("languageContext");
const language = yield languageContext.getLanguage();
...
}
For more on this you can check, getContext