Ad

Props Value Based On A Stored Cookie

- 1 answer

Based on a specific value from a stored cookie (selectedRetailerId) the source (API endpoint) is different.

I'm trying to store the value of the cookie in a variable called retailer_id and use that to make sure the correct endpoint is called.

Here's what I'm trying...

<OTHER CODE IS REDACTED>

ReactDOM.render(
  function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
  }

  var retailer_id = getCookie(selectedRetailerId);

  <DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
  document.getElementById('deliveryOptionsContainer')
)

But this returns a Uncaught SyntaxError. Probably because this piece of code should not be in ReactDOM.render.

Uncaught SyntaxError: http://localhost:8000/src/app.js: Unexpected token (130:2)
  128 |   }
  129 | 
> 130 |   var retailer_id = getCookie(selectedRetailerId);
      |   ^
  131 | 
  132 |   <DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
  133 |   document.getElementById('deliveryOptionsContainer')

What is the right way to do this with React?

Ad

Answer

Try this:

// Defined somewhere outside ReactDOM.render (I'd recommend a helpers.js file)
// If you move it out of this file, be sure to import / require it
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

ReactDOM.render(
  <DeliveryOptionsTable source={"http://<REDACTED>/delivery_options/" + getCookie(selectedRetailerId)} />,
  document.getElementById('deliveryOptionsContainer')
)
Ad
source: stackoverflow.com
Ad