jarivak
jarivak

Reputation: 858

How to get UserId from localStorage

I'm trying to build a blog, on a certain end point I want to list all the blogs created by specific user only, so i have stored the user info in Local Storage and I'm trying to get the username of the same, so that i can send the username to backend to get the blogs posted by that specific username.

set cookie

import cookie from 'js-cookie';

export const setCookie = (key, value) => {
    if (process.browser) {
        cookie.set(key, value, {
            expires: 1
        });
    }
};

get cookie

// get cookie
export const getCookie = key => {
    if (process.browser) {
        return cookie.get(key);
    }
};

set LocalStorage

export const setLocalStorage = (key, value) => {
    if (process.browser) {
        localStorage.setItem(key, JSON.stringify(value));
    }
};

isAuth action

export const isAuth = () => {
        if(process.browser ) {
            const cookieChecked = getCookie('token')
            if(cookieChecked){
                if(localStorage.getItem('user')){
                    return JSON.parse(localStorage.getItem('user'))
                }else{
                    return false;
                }
            }
        }
    }

This is the Info that I have stored in the Local Storage

{_id: "5ece659149421c1f18c0c756", username: "2asjvwxkq", name: "test3", email: "[email protected]", role: 0}
email: "[email protected]"
name: "test3"
role: 0
username: "2asjvwxkq"
_id: "5ece659149421c1f18c0c756"

I tried doing const username = isAuth() && isAuth().username

But it is returning undefined

I want to send the username as a props to a component but the variable username is getting me undefined value.

Update : JSON.stringify(username) gives me the username but i am unable to send the same to backend


Screenshot of LocalStorage key

Upvotes: 2

Views: 5541

Answers (2)

Nitin
Nitin

Reputation: 598

Try doing

Suggestion 1 :

const username = isAuth() ? isAuth().username : '' or use useEffect() wherever necessary .


Suggestion 2 :

Instead of sending the props , directly call the function
isAuth() inside the component you wanted to send in the first place ( if doing so won't affect anything ) and just to debug try doing JSON.stringify(user)

Upvotes: 1

Bahtiyar
Bahtiyar

Reputation: 192

I made simple for you. I think problem is json.parse method. look my example

export const isAuth = () => {

    if (localStorage.getItem('user')) {
        return localStorage.getItem('user');
    } else {
        return false;
    }
}

and in my app.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import {isAuth} from './isAuth'

function App() {
  localStorage.setItem('user', 'bahtiyar');
  const userName=isAuth();

  return (
    <div className="App">
     <div>{userName}</div>
    </div>
  );
}

export default App;

look result: enter image description here

Upvotes: 0

Related Questions