How to access Context within a Class Component for react native?
I want to use my Context in a class component (MyEventsScreen), but whenever I do so, I get an error saying it is an invalid hooks call.
Here is MyEventsScreen.js (I've simplified it to be brief):
import { useAuthState } from "../contexts/authContext";
export default class MyEventsScreen extends Component {
render() {
return (
<View>
<Text></Text>
</View>
}
I have my authContext.js here:
import React from "react";
import { authReducer } from "../reducers/authReducer";
const AuthStateContext = React.createContext();
const AuthDispatchContext = React.createContext();
function AuthProvider({ children }) {
const [state, dispatch] = React.useReducer(authReducer, {
isLoading: true,
isSignout: false,
userToken: null,
email: null,
userID: null,
});
return (
<AuthStateContext.Provider value={state}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
</AuthDispatchContext.Provider>
</AuthStateContext.Provider>
);
}
function useAuthState() {
const context = React.useContext(AuthStateContext);
if (context === undefined) {
throw new Error("useAuthState must be used within a AuthProvider");
}
return context;
}
function useAuthDispatch() {
const context = React.useContext(AuthDispatchContext);
if (context === undefined) {
throw new Error("useAuthDispatch must be used within a AuthProvider");
}
return context;
}
export { AuthProvider, useAuthState, useAuthDispatch };
I have an authReducer.js here:
export const authReducer = (prevState, action) => {
switch (action.type) {
case "SIGN_IN":
return {
...prevState,
email: action.email,
isSignout: false,
userToken: action.token,
};
default:
return prevState;
}
};
Any help would be appreciated!
from Recent Questions - Stack Overflow https://ift.tt/3mHbzOu
https://ift.tt/eA8V8J
Comments
Post a Comment