React context delay on authorization - javascript

I'm building and app on next and node.
Trying to add authorization to admin pages, but when i try to get my auth context it returns empty for several times and after that returns the context data.
This is the auth-context.js
import React, { useCallback, useState } from "react";
import { useRouter } from "next/router";
import axios from "../lib/api/axios";
import { User } from "./types";
interface AuthState {
token: string | null;
}
interface UserState {
user: User | null;
}
type AuthContextType = {
authState: AuthState;
setAuthState: (userAuthInfo: { data: string }) => void;
isUserAuthenticated: () => boolean;
logOut: () => void;
isAdmin: () => boolean;
user: UserState;
};
const AuthContext = React.createContext<AuthContextType>({} as AuthContextType);
const { Provider } = AuthContext;
interface childrenProps {
children: React.ReactNode;
}
function setToken(data: string) {
window.localStorage.setItem("token", data);
}
function logOut() {
localStorage.removeItem("token");
}
const AuthProvider = ({ children }: childrenProps) => {
const [authState, setAuthState] = React.useState<AuthState>({
token: "",
});
const [user, setUser] = useState<UserState>({
user: null,
});
const getData = async () => {
try {
const { data } = await axios.get(`/user`);
const responseUser = data as User;
setUser({
user: responseUser,
});
} catch {
console.log("something went wrong");
}
};
const isAdmin = useCallback(() => {
return user?.user?.admin ?? false;
}, [user]);
const setUserAuthInfo = ({ data }: { data: string }) => {
setToken(data);
setAuthState({
token: data,
});
};
const isUserAuthenticated = (): boolean => {
return !authState.token ? false : true;
};
React.useEffect(() => {
if (typeof window !== undefined && window.localStorage.getItem("token")) {
const token = localStorage.getItem("token");
setAuthState({ token });
}
}, []);
React.useEffect(() => {
if (authState.token) {
const user = getData();
}
}, [authState]);
return (
<Provider
value={{
authState,
setAuthState: (userAuthInfo: { data: string }) =>
setUserAuthInfo(userAuthInfo),
isUserAuthenticated,
logOut,
isAdmin,
user,
}}
>
{children}
</Provider>
);
};
export { AuthContext, AuthProvider, logOut };
This is the control for the admin page
import { useContext, useEffect } from "react";
import { NavbarAdmin } from "../../components/adminNav";
import LayoutAdmin from "../../layout/admin";
import styles from "../../styles/Home.module.css";
import { AuthContext } from "../../lib/auth-context";
import { useRouter } from "next/router";
export default function Home() {
const {user} = useContext(AuthContext);
const router = useRouter();
useEffect(() => {
if (user.user?.admin === false || user.user === null) {
router.push("/access-denied");
}
}, [user.user?.admin]);
return (
<LayoutAdmin>
<div className={styles.container}>
<a>Name</a>
<a>Email</a>
<a>id</a>
</div>
</LayoutAdmin>
);
}
When i try to print user name etc. like this, it works flawless but when i try the codeblock on bellow. It always redirects me the access denied page.
import { useContext } from "react";
import { AuthContext } from "../lib/auth-context";
export default function aboutUs(){
// eslint-disable-next-line react-hooks/rules-of-hooks
const { user } = useContext(AuthContext);
return(
<>
<a>We are a Company!</a>
<a>{user.user?.name}</a>
</>
)
}
When i try to console log user on the admin page, this is the result.
image

Related

Unable to process request due to missing initial state( Firebase)

A user of my website encountered an error message while attempting to sign up using GitHub on my React site from his chrome browser(mobile). I have integrated Firebase GitHub sign-in with the popup method.
Unable to process request due to missing initial state. This may happen if browser sessionStorage is inaccessible or accidentally cleared.
Code for signup:
import { useEffect, useState } from "react"
import { GithubAuthProvider, signInWithPopup } from "firebase/auth"
import { auth } from "../firebase/config"
import { createUserProfileDocument } from "../firebase/createUserProfileDocument"
import { useAuthContext } from "./useAuthContext"
export const useSignup = () => {
const [error, setError] = useState(false)
const [isPending, setIsPending] = useState(false)
const [isCancelled, setIsCancelled] = useState(false)
const provider = new GithubAuthProvider()
const { dispatch } = useAuthContext()
const signup = async () => {
setError(null)
setIsPending(true)
try {
const res = await signInWithPopup(auth, provider)
if (!res) {
throw new Error("Could not complete signup")
}
const user = res.user
await createUserProfileDocument(user)
dispatch({ type: "LOGIN", payload: user })
if (!isCancelled) {
setIsPending(false)
setError(null)
}
} catch (error) {
if (!isCancelled) {
setError(error.message)
setIsPending(false)
}
}
}
useEffect(() => {
return () => setIsCancelled(true)
}, [])
return { signup, error, isPending }
}
useAuthContext code:
import { useContext } from "react"
import { AuthContext } from "../context/AuthContext"
export const useAuthContext = () => {
const context = useContext(AuthContext)
if (!context) {
throw Error("useAuthContext must be used inside an AuthContextProvider")
}
return context
}
AuthContext code
import { createContext, useEffect, useReducer } from "react"
import { onAuthStateChanged } from "firebase/auth"
import { auth } from "../firebase/config"
import { authReducer } from "../reducers/authReducer"
export const AuthContext = createContext()
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null,
authIsReady: false,
})
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
dispatch({ type: "AUTH_IS_READY", payload: user })
})
return unsubscribe
}, [])
return (
<AuthContext.Provider value={{ ...state, dispatch }}>{children}</AuthContext.Provider>
)
}
firebaseConfig object:
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
}
initializeApp(firebaseConfig)
const db = getFirestore()
const auth = getAuth()
export { auth, db, logEvent }

React router PrivateRoute keeps redirecting to the login page

I'm having problem with privateRoute it should be redirecting to the Home page after signin but it keeps redirecting to '/signin' page. everything is working fine if I remove PrivateRoute im not sure I'm beginner with react and it's my first time using firebase auth is there any way to fix this problem I'm sorry my code is messy
import React, {useEffect, useState} from 'react'
import firebase from 'firebase'
import StyledFirebaseAuth from 'react-firebaseui/FirebaseAuth'
import { Redirect, useHistory } from 'react-router-dom';
import axios from 'axios';
import { useAuth } from "../context/AuthContext";
import { Route, withRouter } from 'react-router-dom';
var uiconfig = {
signInFlow: 'popup',
signInSuccessUrl:'/',
signInOptions : [
firebase.auth.EmailAuthProvider.PROVIDER_ID],
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
return true;
}
}
};
const signOut = () => {
firebase.auth().signOut().then(function(){
return console.log('signout');
}).catch(() => {
console.error("error signout");
})
return <Redirect to='/signin'></Redirect>
}
var Cuser = null
const PrivateRoute = ({component: Component, ...rest}) => {
const [user, setUser] = useState(false)
const {currentUser} = useAuth()
console.log(Cuser)
return (
<Route {...rest} render={props => {
if(Cuser){
return <Component {...props}></Component>
} else {
return <Redirect to="/signin" />
}
}} ></Route>)
}
const Signup = () => {
const {history} = useHistory()
useEffect(() => {
const authOberver = firebase.auth().onAuthStateChanged((user) => {
setUser(user)
});
return authOberver
})
const [user, setUser] = useState(null)
if(user){
axios.post("http://localhost:4000/notes", {
email: user.email,
})
Cuser = true
}
return (
<>
<div>Signin / Register</div>
<StyledFirebaseAuth uiConfig={uiconfig} firebaseAuth={firebase.auth()}></StyledFirebaseAuth>
</>
)
}
export {signOut}
export default Signup;
export {PrivateRoute};
I tried to create a separate file for current user and using currentUser to check if the user is logged in or not but still happing the same problem
import React, { useContext, useEffect, useState } from "react";
import { auth } from "../firebase";
import firebase from "firebase";
import axios from 'axios'
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'
const AuthContext = React.createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
useEffect(() => {
const unsubscribed = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
})
return unsubscribed
}, []);
const value = {
currentUser,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
I think the problem is that you are using the variable Cuser to decide what component to render. So even if Cuser is set to true after signup, when the component gets re-rendered, it's value gets back to being null which is why it goes to else {return <Redirect to="/signin" />} block.
You can modify you AuthContext to store the login status in state. In below code, lets say cUser:
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
cont [cUser, setCUser] = useState(false);
useEffect(() => {
const unsubscribed = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
})
return unsubscribed
}, []);
const value = {
currentUser,
cUser: cUser,
setCUser: setCUser,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
And then use setCUser to set and check the value
import React, {useEffect, useState} from 'react'
import firebase from 'firebase'
import StyledFirebaseAuth from 'react-firebaseui/FirebaseAuth'
import { Redirect, useHistory } from 'react-router-dom';
import axios from 'axios';
import { useAuth } from "../context/AuthContext";
import { Route, withRouter } from 'react-router-dom';
var uiconfig = {
signInFlow: 'popup',
signInSuccessUrl:'/',
signInOptions : [
firebase.auth.EmailAuthProvider.PROVIDER_ID],
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
return true;
}
}
};
const signOut = () => {
firebase.auth().signOut().then(function(){
setCUser(false);
return console.log('signout');
}).catch(() => {
console.error("error signout");
})
return <Redirect to='/signin'></Redirect>
}
var Cuser = null
const PrivateRoute = ({component: Component, ...rest}) => {
const [user, setUser] = useState(false)
const {currentUser, cUser, setCUser} = useAuth()
console.log(Cuser)
return (
<Route {...rest} render={props => {
if(cUser){
return <Component {...props}></Component>
} else {
return <Redirect to="/signin" />
}
}} ></Route>)
}
const Signup = () => {
const {history} = useHistory()
useEffect(() => {
const authOberver = firebase.auth().onAuthStateChanged((user) => {
setUser(user)
});
return authOberver
})
const [user, setUser] = useState(null)
if(user){
axios.post("http://localhost:4000/notes", {
email: user.email,
})
setCUser(true);
}
return (
<>
<div>Signin / Register</div>
<StyledFirebaseAuth uiConfig={uiconfig} firebaseAuth={firebase.auth()}></StyledFirebaseAuth>
</>
)
}
export {signOut}
export default Signup;
export {PrivateRoute};

Function is not getting called anymore, when trying to dispatch a type

I am currently trying to access my data using the Spotify API. This works very well. Thats the function I am using to get my Data. I assume the other stuff is not important. I can post that, if you need that.
export const getSpotifyUser = (access_token:string) =>{
setAuthorizationHeader(access_token)
axios.get('https://api.spotify.com/v1/me').then((res) => {
console.log(res.data)
})
}
I have set up a redux store and trying to put the credentials into the store, by dispatching the right type (SET_USER).
export const getSpotifyUser = (access_token:string) => (dispatch: any) => {
console.log("function is not called") // Function is not even called why ?
setAuthorizationHeader(access_token)
axios.get('https://api.spotify.com/v1/me').then((res) => {
console.log(res.data)
dispatch ({
type: SET_USER,
payload: res.data
})
}
but as soon as I use dispatch, the function is no longer called.
I really do not see my mistake. Is that a typescript error ?. ( I am using react typescript)
store.js
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './rootReducer'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
)
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
export default store
rootReducer.ts
import { combineReducers } from 'redux'
import userReducer from './User/userReducer'
const rootReducer = combineReducers({
user: userReducer,
})
export default rootReducer
userReducer.ts
import { AnyAction } from 'redux'
import { SET_USER } from './userTypes'
interface Credentials {
username: string
email: string
profilepicture: string
id: number
}
interface InitialState {
authenticated: boolean
loadding: boolean
credentials?: Credentials
}
const initialState: InitialState = {
authenticated: false,
loadding: false,
credentials: {} as Credentials,
}
const reducer = (state = initialState, action: AnyAction) => {
switch (action.type) {
case SET_USER: {
return {
...state,
loading: false,
credentials: action.payload,
}
}
default:
return state
}
}
export default reducer
Login.tsx ( I am making the login here. It is working fine, if am not using dispatch
import { IonButton } from '#ionic/react'
import React, { useEffect } from 'react'
import {
getAuthorizeHref,
getHashParams,
removeHashParamsFromUrl,
getSpotifyUser,
} from '../../Helpers/login'
const Login: React.FC = () => {
// const user = useSelector((state: RootState) => state.user.credentials)
useEffect(() => {
const hashParams = getHashParams()
const access_token = hashParams.access_token
// const expires_in = hashParams.expires_in
removeHashParamsFromUrl()
getSpotifyUser(access_token)
}, [])
return (
<IonButton onClick={() => window.open(getAuthorizeHref(), '_self')}>
)}
export default Login
since you're using typescript with react, I believe you have added the getSpotifyUser function to your interface, now if you want to access that i think you should call it like this
props.getSpotifyUser(access_token)
and finally add it to your connect as a dispatch function that's wrapping your component
your login component should be like this one
import { IonButton } from '#ionic/react'
import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import {
getAuthorizeHref,
getHashParams,
removeHashParamsFromUrl,
getSpotifyUser,
} from '../../Helpers/login'
interface ILogin {
getAuthorizeHref: () => any;
getHashParams: () => any;
removeHashParamsFromUrl: () => any;
getSpotifyUser: (access_token) => any;
}
const Login: React.FC = (props: ILogin) => {
// const user = useSelector((state: RootState) => state.user.credentials)
useEffect(() => {
const hashParams = props.getHashParams()
const access_token = hashParams.access_token
// const expires_in = hashParams.expires_in
props.removeHashParamsFromUrl()
props.getSpotifyUser(access_token)
}, [])
return (
<IonButton onClick={() => window.open(props.getAuthorizeHref(), '_self')}>
)}
export default connect(null, {getAuthorizeHref, getHashParams, removeHashParamsFromUrl, getSpotifyUser})(Login)
Basicly Shamim has given the right answer.Any function that uses that dispatch is a redux action, and you have to follow the docs specifically to call that function. You have to use connect to dispatch actions. As an alternative you can use the dispatchHook. If am wrong please please correct me !!!!
Thats the right code I just had to correct Login.tsx
import { IonApp, IonButton } from '#ionic/react'
import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import {
getAuthorizeHref,
getHashParams,
removeHashParamsFromUrl,
getSpotifyUser,
} from '../../Helpers/login'
const style = {
Logo: {
display: 'flex',
justifyContent: 'space-evenly',
color: 'white',
position: 'relative',
top: '70%',
} as const,
}
const Login: React.FC = (props: any) => {
// const user = useSelector((state: RootState) => state.user.credentials)
useEffect(() => {
const hashParams = getHashParams()
const access_token = hashParams.access_token
// const expires_in = hashParams.expires_in
removeHashParamsFromUrl()
console.log('halloeuseeffect')
props.getSpotifyUser(access_token)
console.log('halloeuseeffect')
}, [])
return (
<IonApp>
<IonButton onClick={() => window.open(getAuthorizeHref(), '_self')}>
knsnan
</IonApp>
)
}
export default connect(null, {
getSpotifyUser,
})(Login)

Getting error when calling an action from container in react-redux

I am integrating redux with my react-native app. I have moved my state and action management to Container and integrated the container with component using 'connect'.
App.js
const AppNavigator = createSwitchNavigator({
SplashScreen: SplashScreen,
render() {
return(
<Provider store={store}>
<AppNavigator/>
</Provider>
)
}
});
const store = createStore(reducer);
export default createAppContainer(AppNavigator);
SignIn.js
import React from "react";
import {View} from "react-native";
import authenticateUser from "../../../services/api/authenticateUser";
const SignIn = (props) => {
const authenticate = async () => {
try {
return await authenticateUser.get('/abc', {
params: {
code,
}
});
}
catch (e) {
}
}
const validateUserCredentials = (isValid) => {
authenticate().then(response => {
const responseData = response.data;
props.updateEventRules(responseData);
});
}
}
return (
<View></View>
);
export default SignIn;
Sign-InContainer.js
import {eventRulesUpdated} from '../../../actions/actions';
import {connect} from 'react-redux';
import SignIn from './signin-screen';
const mapStateToProps = (state) => ({});
const mapDispatchToProps = dispatch => {
return {
updateEventRules: rules => {
dispatch(eventRulesUpdated(rules))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
When running the app I am getting an error that - props.updateEventRules() is not a function.
Can anyone please help me what am I doing wrong?
You should have the connect functions inside Signin.js like this
import React from "react";
import {View} from "react-native";
import authenticateUser from "../../../services/api/authenticateUser";
const SignIn = (props) => {
const authenticate = async () => {
try {
return await authenticateUser.get('/abc', {
params: {
code,
}
});
}
catch (e) {
}
}
const validateUserCredentials = (isValid) => {
authenticate().then(response => {
const responseData = response.data;
props.updateEventRules(responseData);
});
}
}
return (
<View></View>
);
const mapStateToProps = (state) => ({});
const mapDispatchToProps = dispatch => {
return {
updateEventRules: rules => {
dispatch(eventRulesUpdated(rules))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);

Redux saga call(fetch...) function not returning any thing in react native

I am new to Redux-Saga, have knowledge of Redux.
I am creating a login process using React Native and Redux, Redux-Saga, This is my first redux-saga project and I am not able to fetch the response from call function of the saga.
It just not run the code after yield call(UserService.loginUserApi, params); below is the code.
LoginContainer.js
import React from 'react'
import { Platform, Text, View, Button, ActivityIndicator, Image } from 'react-native'
import { connect } from 'react-redux'
import { ApplicationStyles, Helpers, Images, Metrics } from 'App/Theme'
import LoginActions from 'App/Actions/LoginAction'
class LoginContainer extends React.Component {
componentDidMount() {
}
render() {
return (
<View
style={[
Helpers.fill,
Helpers.rowMain,
Metrics.mediumHorizontalMargin,
Metrics.mediumVerticalMargin,
]}
>
{this.props.isLoading ? (
<View>
<ActivityIndicator size="large" color="#0000ff" />
<Text>{JSON.stringify(this.props.isLoading)}</Text>
</View>
) : (
<View>
<Text >To get started, edit App.js </Text>
{this.props.loginError ? (
<Text >{JSON.stringify(this.props.loginError)}</Text>
) : <Text >{JSON.stringify(this.props.userDetails)}</Text>}
<Button
onPress={() => this.props.loginUser({
"email": "eve.holt#reqres.in",
"password": "cityslicka"
})}
title="Refresh"
/>
</View>
)}
</View>
)
}
}
const mapStateToProps = (state) => {
return ({
userDetails: state.login.userDetails,
isLoading: state.login.isLoading,
loginError: state.login.loginError,
})
};
const mapDispatchToProps = (dispatch) => ({
loginUser: (payload) => dispatch(LoginActions.loginUser(payload)),
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginContainer)
LoginAction.js
const { Types, Creators } = createActions({
// Fetch user informations
loginUser: ['params'],
// The operation has started and is loading
loginLoading: ['value'],
// User informations were successfully fetched
loginUserSuccess: ['user'],
// An error occurred
loginUserError: ['errorMessage'],
})
export const LoginTypes = Types
export default Creators
LoginSaga.js
import { put, call, take } from 'redux-saga/effects'
import LoginActions, { LoginTypes } from 'App/Actions/LoginAction'
import { UserService } from 'App/Services/UserService'
export function* getLogin() {
// while (true) {
// console.log(LoginActions.loginUser());
const action = yield take(LoginTypes.LOGIN_USER);
const { params } = action;
console.log("params", params);
// yield put(LoginActions.loginLoading(true))
let response1 = yield call(UserService.loginUserApi, params);
console.log("it doesnot print anything", response1);
// LoginActions.loginUserError('test');
// console.log("RUN RUn");
// if (response1) {
// console.log("USER", response1);
// yield put(LoginActions.loginUserSuccess(response1))
// } else {
// yield put(
// LoginActions.loginUserError('There was an error while fetching user informations.')
// )
// }
// }
}
Sagas/index.js
import { getLogin } from './LoginSaga'
import { LoginTypes } from 'App/Actions/LoginAction'
export default function* root() {
yield all([
takeLatest(LoginTypes.LOGIN_USER, getLogin),
])
}
LoginReducers.js
import { createReducer } from 'reduxsauce'
import { LoginTypes } from 'App/Actions/LoginAction'
const INITIAL_STATE = {
userDetails: {},
isLoading: false,
loginError: null,
}
export const loginUserError = (state, { errorMessage }) => {
alert();
console.log(errorMessage);
return ({
...state,
userDetails: {},
isLoading: false,
loginError: errorMessage,
})
}
export const loginUserSuccess = (state, { user }) => ({
...state,
userDetails: user,
isLoading: false,
loginError: null,
})
export const loginLoading = (state, { value }) => ({
...state,
userDetails: {},
isLoading: value,
loginError: null,
})
export const loginReducer = createReducer(INITIAL_STATE, {
[LoginTypes.LOGIN_USER_SUCCESS]: loginUserSuccess,
[LoginTypes.LOGIN_USER_ERROR]: loginUserError,
[LoginTypes.LOGIN_LOADING]: loginLoading,
})
Store/index.js
import configureStore from './CreateStore'
import rootSaga from 'App/Sagas'
import { loginReducer } from 'App/Reducers/LoginReducers'
export default () => {
const rootReducer = combineReducers({
login: loginReducer,
})
return configureStore(rootReducer, rootSaga)
}
ConfigureStore.js
import { applyMiddleware, compose, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { persistReducer, persistStore } from 'redux-persist'
/**
* This import defaults to localStorage for web and AsyncStorage for react-native.
*
* Keep in mind this storage *is not secure*. Do not use it to store sensitive information
* (like API tokens, private and sensitive data, etc.).
*
* If you need to store sensitive information, use redux-persist-sensitive-storage.
* #see https://github.com/CodingZeal/redux-persist-sensitive-storage
*/
import storage from 'redux-persist/lib/storage'
const persistConfig = {
key: 'root',
storage: storage,
/**
* Blacklist state that we do not need/want to persist
*/
blacklist: [
// 'auth',
],
}
export default (rootReducer, rootSaga) => {
const middleware = []
const enhancers = []
// Connect the sagas to the redux store
const sagaMiddleware = createSagaMiddleware()
middleware.push(sagaMiddleware)
enhancers.push(applyMiddleware(...middleware))
// Redux persist
const persistedReducer = persistReducer(persistConfig, rootReducer)
const store = createStore(persistedReducer, compose(...enhancers))
const persistor = persistStore(store)
// Kick off the root saga
sagaMiddleware.run(rootSaga)
return { store, persistor }
}
userServices.js
import { Config } from 'App/Config'
import { is, curryN, gte } from 'ramda'
loginUserApi = (userdetails) => {
console.log("IN loginUserApi ", userdetails);
return fetch(Config.API_URL + 'login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userdetails.email,
password: userdetails.password,
})
});
// let data = await response.json();
// console.log(data);
// return data;
}
export const UserService = {
loginUserApi,
}
Maybe this call is throwing an error,
let response1 = yield call(UserService.loginUserApi, params);
try to wrap it in a "try/catch" block maybe you have to handle an error case

Categories