How to read a cookie with react-cookie? - reactjs

I am building a FullStack App with React and Express.
I am using react-cookie.
After submit a form i set cookies in my browser then i render a new page in my application.
setCookie("jwt", `${data.jwt}`, {
path: "/"
});
setCookie("user", `${data.name}`, {
path: "/"
});
Then i want to read a cookie in that component and i do not know how can i do it.
So if someone have any idea how to do it please write below :)
Thanks :)

You can use the hook useCookies like this:
import { useCookies } from 'react-cookie';
const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
const myCookie = cookies.get('cookie-name')

You could use much simpler way like this
(make sure you have installed react-cookie FIRST!)
import { useCookies } from 'react-cookie';
const [cookies, setCookie, removeCookie] = useCookies();
// set Cookie
setCookie('access_token','your_token_value_here')
// read cookie with
console.log(cookies.access_token)

Related

The cookies are not store in the browser

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('jwt', "chalmeraputt");
console.log(cookies.get("jwt"));
I have using this code to add cookie but could not get it and also not showed in the browser also.
This should work fine:
import Cookies from "universal-cookie";
function App() {
const cookies = new Cookies();
cookies.set("cookie", "chocolate_chip", { path: "/" });
return <div>{cookies.get("cookie")}</div>;
}
export default App;
A cookie is a piece of data (key-value pairs) stored on the user’s computer by the web browser while browsing a site. Cookies are a reliable mechanism for websites to remember stateful information or record the user’s browsing activity or verify the user's identity.
import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('jwt', 'chalmeraputt', { path: '/' });
console.log(cookies.get('jwt'));
Refer this link

How to set Base URL in Axios, based on a user input - React Native

I am building an app where the user connects to a server by entering the URL when logging in.
Each server provides an API and I can't hard-code the value for the BaseURL when creating the Axios client instance. I somehow need to globally store the URL and set it based on the user input in the login form.
So I would like to know what is a proper way to do this. I am really not sure what is the best approach to dynamically store a value that I can access when creating the API connection. Any ideas and best practice suggestions are welcome.
Here is the code for creating the API connection: client.js
import { create } from 'apisauce';
const api = create({
baseURL: "BASE_URL_FROM_USER_INPUT" + "server/odata/"
});
export default api;
This is how I use the API: users.js
import api from './client';
const getUsers = () => api.get("/users");
export default {
getUsers
}
This is how I will get my data:
import React, { useState, useEffect } from "react";
import usersApi from '../api/users';
const TestScreenAuthenticated = ({navigation}) => {
const [users, setUsers] = useState([]);
useEffect(() => {
loadUsers();
});
const loadUsers = async () => {
const response = await usersApi.getUsers();
setUsers(response);
}
...
};
export default TestScreenAuthenticated;
you can use the localStoreto store the baseUrl.
//save the value
localStore.setItem('baseUrl', value)
//read the value
localStore.getItem('baseUrl')
If you can use the .env file in your project and put the web service address there. This file is out of reach of the user viewing the site and will not be able to edit it
this link:
https://create-react-app.dev/docs/adding-custom-environment-variables/

How to initialize firebase in gatsby?

I'm stuck on making firebase work in my gatsby application that uses Redux with Redux-sagas. I know about the existence of firebase-sagas but I'm trying to make without using it.
I'm trying to init firebase auth by:
import * as firebase from 'firebase/app';
import 'firebase/auth';
export const app = firebase.initializeApp(
{
apiKey : "apiKey",
authDomain : "project.firebaseapp.com",
databaseURL : "https://project.firebaseio.com",
projectId : "project",
storageBucket : "project.appspot.com",
appId : "appId"
}
)
export const authRef = () => app.auth(); //also tried: firebase.auth() and firebase.auth(app)
//firebase.auth returns a function, but firebase.auth() throws error
I have the following config on my gatsby-node.js:
const path = require('path');
exports.onCreateWebpackConfig = ({ actions, plugins, loaders, getConfig }) => {
const config = getConfig()
config.resolve = {
...config.resolve,
mainFields: ['module', 'browser', 'main'],
alias: {
...config.resolve.alias,
['firebase/app'] : path.resolve(__dirname, 'node_modules/firebase/app/dist/index.cjs.js'),
['firebase/auth'] : path.resolve(__dirname, 'node_modules/firebase/auth/dist/index.cjs.js'),
}
}
actions.replaceWebpackConfig(config)
}
It trows the error:
{ [M [Error]: The XMLHttpRequest compatibility library was not found.]
code: 'auth/internal-error',
message: 'The XMLHttpRequest compatibility library was not found.' }
I think it's some problem related to webpack. I would love any insights on this problem :)
As Gatsby builds pages in a server environment, you can't access Firebase during Gatsby build time. Firebase calls (using the Web SDK) have to happen when the user is on a browser/client environment.
One solution to this problem is creating a function like so:
firebase.js:
import firebase from '#firebase/app';
import '#firebase/auth';
import '#firebase/firestore';
import '#firebase/functions';
const config = {
... firebase config here
};
let instance;
export default function getFirebase() {
if (typeof window !== 'undefined') {
if (instance) return instance;
instance = firebase.initializeApp(config);
return instance;
}
return null;
}
This file returns a function, which returns an instance of Firebase if the user has the global window available (e.g. on the browser). It also caches the Firebase instance to ensure it cannot be reinitialised again (in case of the user changing page on your website).
In your components, you can now do something similar to the following:
import getFirebase from './firebase';
function MyApp() {
const firebase = getFirebase();
}
As Gatsby will try to build this page into HTML during gatsby build, the firebase const will return null, which is correct, as the Firebase Web SDK cannot initialise on a server environment. However, to make use of Firebase on your website, you need to wait until Firebase is available (so the user has to have loaded your website), so we can make use of Reacts useEffect hook:
import React { useEffect } from 'react';
import getFirebase from './firebase';
function MyApp() {
const firebase = getFirebase();
useEffect(() => {
if (!firebase) return;
firebase.auth().onAuthStateChanged((user) => { ... });
}, [firebase]);
}
This works as Firebase is being used in a browser environment and has access to the browser, which is needed for the Web SDK to work.
It does have drawbacks; your compo have to return null in instances when you need Firebase to display content, which will mean your HTML build on the server will not contain any HTML, and it'll be injected via the client. In most cases though, such as an account page, this is fine.
If you need access to data from say Cloud Firestore to display page content, you're best using the Admin SDK to fetch content and add it to GraphQL during Gatsby build. That way it will be available on the server during build time.
Sorry if that was a waffle or not clear!

How to get User information from JWT cookie in NextJS / ReactJS

I am learning about Next.JS and React and was wondering if it is possible to get user details from the cookie storing the JWT.
I have managed to set the JWT as the cookie and can log it successfully and have also managed to decode it but can't find anything on how to get username, id, etc from it. Here's what I have so far:
import React from "react";
import App from "../components/App.js";
import cookie from "react-cookies";
import jwt_decode from "jwt-decode";
export default class Dashboard extends React.Component {
static async getInitialProps() {
const token = cookie.load("jwt");
return { token };
}
constructor(props) {
super(props);
this.state = props.token;
}
render() {
const current_user = jwt_decode(this.props.token, { header: true });
return (
<App>
<p>Username: {current_user.username}</p>
</App>
);
}
}
Ideally, i'd like to be able to set the cookie value to a user variable and extract properties from it, e.g. current_user.username. Unless i've got it completely wrong and have missed out something really important! Any help would be massively appreciated!
You can use this parseJwt function to extract the user data:
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
console.log(parseJwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'))
It will extract the data inside a jwt token and will return an object
You can use npm package. Simply run npm install jwt-decode in the cmd and use the following code:
import jwt_decode from "jwt-decode";
const token = "eyJ0eXAiO.../// jwt token";
const decoded = jwt_decode(token);

_universalCookie.Cookies is not a constructor error in ReactJS

How to use universal-cookie in ReactJS? I'm getting this error "_universalCookie.Cookies is not a constructor".
import { Cookies } from 'universal-cookie';
...
const cookies = new Cookies();
cookies.set('myTokenCookies', 'response.data.token', { expires: 7, path: '/' });
console.log(cookies.get('myTokenCookies'));
Do
import * as Cookies from 'universal-cookie';
to fix this. I chose to ditch universal-cookie and use the detect-browser package instead.
You need to import Cookies as a default export:
import Cookies from 'universal-cookie';
and not
import { Cookies } from 'universal-cookie';

Resources