Home > Net >  check if url contains string and save value into cookie
check if url contains string and save value into cookie

Time:07-07

I want to implement a referral system. For that I need to check page url, if it contains something like this: https://myurl.com/referralID=123

If the url does contain a referral then I need to save the ID value (123 in this example) into a cookie, which I will use later on (I will check if this cookie exists).

I've neither worked with cookies before, nor that experienced with React.

import React, { useEffect, Fragment } from "react"
import { Helmet } from "react-helmet"
import { useRuntime } from "vtex.render-runtime"
import "./style.global.css"

checkCookie() {
    let refId = window.location.href.indexOf('refferalID=123')

    if ( refId ) {
    // document.cookie = `refferalID=${value}`
        document.cookie = '123'
    }   
        else 
    {
        console.log("no refferal ID :(")
    }
}

const Head = ({}) => {
    return (
        <Fragment>
            <Helmet>                 
                {checkCookie() }
            </Helmet>
        </Fragment>
    )
}

Head.propTypes = {}

export default Head

How could I check url not only for refferalID=123, but for any ID and save this value into a cookie that could be sent afterwards?

CodePudding user response:

To save and retrieve cookie by name,without using additional library, you can use functions below:

export const setCookie = (cname, cvalue) => {
  var d = new Date();
  d.setTime(d.getTime()   24 * 60 * 60 * 1000);
  var expires = 'expires='   d.toUTCString();
  document.cookie = cname   '='   cvalue   ';'   expires   ';path=/';
};

export const getCookie = cname => {
  var name = cname   '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i  ) {
    var c = ca[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
};

To extract query parameter from request, you can use URLSearchParams like this:

const queryParams = new URLSearchParams(window.location.search)
 const id= queryParams.get("refferalID")
  if(id) {
  //save id in cookie
  setCookie("refferalID",id); 

}

Later, if you want to get cookie you can use getCookie function, like this:

const cookie = getCookie("refferalID");

CodePudding user response:

For example, maybe you can follow a path like this

import Cookies from 'universal-cookie';

const queryParams = new URLSearchParams(window.location.search)
const refId = queryParams.get("refferalID")

const cookies = new Cookies();
let idCookie = cookies.get('refferalID')

if(!idCookie) {
    cookies.set('refferalID', refId, { path: '/' });    
}
  • Related