Home > Mobile >  Cannot read properties of null (reading 'user')
Cannot read properties of null (reading 'user')

Time:12-01

I have been trying to solve this issue wherein, I can grab the accessToken after login only? I have been stuck on this

The main problem is, the Token is already looking for it on localstorage, but I'm not even logged in yet. How can I make the user to login first before looking to the local storage

requestMethod.js

import axios from 'axios'

const BASE_URL = 'http://localhost:5000/api'

const TOKEN = JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
  .currentUser.accessToken

export const publicRequest = axios.create({
  baseURL: BASE_URL,
})

export const userRequest = axios.create({
  baseURL: BASE_URL,
  headers: { token: `Bearer ${TOKEN}` },
})

Login.jsx

import { useEffect } from "react"
import { useState } from "react"
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import { login } from "../../redux/apiCalls"
import { userRequest } from "../../requestMethod"

const Login = () => {
    let history = useHistory()
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const dispatch = useDispatch()
    const handleClick = (e) =>{
        e.preventDefault()
        login(dispatch,{username,password})      
        history.push('/home')
        
    }

    useEffect(() =>{
        try {
            
        } catch (error) {
            
        }
    },[])

    return (
        <div style={{display: 'flex', alignItems:"center", justifyContent:"center", height: '100vh', flexDirection: "column"}}>
            <form action="">
            <input style={{padding: 10, marginBottom:20}} value={username}  type="text" placeholder="username" onChange={e => setUsername(e.target.value)} />
            <input style={{padding: 10, marginBottom:20}} value={password} type="password" placeholder="password" onChange={e => setPassword(e.target.value)} />
            <button style={{padding: 10, width: 100}} onClick={handleClick}>Login</button>
            </form>

        </div>
    )
}

export default Login

apicalls.js

import { loginFailure, loginStart, loginSuccess } from './userRedux'

export const login = async (dispatch, user) => {
  dispatch(loginStart())
  try {
    const res = await publicRequest.post('/auth/login', user)
    const TOKEN = JSON.parse(
      JSON.parse(localStorage.getItem('persist:root')).user
    ).currentUser.accessToken
    dispatch(loginSuccess(res.data))
  } catch (error) {
    dispatch(loginFailure())
  }

}

CodePudding user response:

You have to lookup on localstorage first. Just check if localstorage contains token or not. If not, render some message and redirect user to login page.

CodePudding user response:

Use optional chaining(?.):

const TOKEN = JSON.parse(JSON.parse(localStorage.getItem('persist:root'))?.user)
  ?.currentUser?.accessToken;
  • Related