Yassine Soltani
Yassine Soltani

Reputation: 139

JWT decode React

Hello everyone i want to use jwt decode in my react project but when i want to console.log decoded token it shows me errors

the token is fine because the authetication works fine i don't know the problem this is my code

async formSubmit(ev){
    ev.preventDefault()
    const {username, password} = this.state
    try {
        const token = await Axios.post("api/login/", {username, password})
        localStorage.setItem("token", token)
        this.setState({
            loggedIn: true
        })
      var jwtDecode = require('jwt-decode')

      var decoded = jwtDecode(token)
      console.log(decoded)
    } catch (err) {
        this.setState({
            error: "compte inexistant"
        })
    }
}

and this is the error enter image description here

Upvotes: 1

Views: 2882

Answers (1)

Yassine Soltani
Yassine Soltani

Reputation: 139

it's working now i don't know why actually but it's working here's the code :

 formSubmit(ev){
    const {username, password} = this.state
    ev.preventDefault();
    Axios.post("api/login/", {username, password}).then(res => 
    {localStorage.setItem("token", JSON.stringify(res.data.access))
    let decoded = jwt_decode(localStorage.getItem("token"))
     localStorage.setItem('decoded',decoded)
    console.log(decoded)
        this.setState({
            loggedIn: true
        });
   }).catch(e =>{
     this.setState({
            error: "compte inexistant"
        })
   })

Upvotes: 1

Related Questions