2

When user is in page 'a' and there writes something in forms input field then goes from page a to page b and from there back to page a, here if user wants to get data from url, there could be two with the same name for example this is url ?name=james&name=alex my question is how to get that latest 'name' for example name name=alex is the new one. Here is how i get from url:

const query = window.location.toString().split("?")[1];

const urlParams = new URLSearchParams(query);


const Name = urlParams.get("name") || props.order?.name;
<Form.Item label={t( "orders.name")} name="name" initialValue={Name || ""}>
  <Input type="string" />
</Form.Item>
kunal panchal
  • 798
  • 5
  • 21
  • Each param should really have its own name, e.g. `name=james&name1=alex`, but you can use the same param name if you want. Take a look here: https://stackoverflow.com/questions/64319356/retrieve-multiple-key-values-from-query-string-with-same-parameter – Dshiz Mar 31 '21 at 13:08
  • yes should, but when i come back to edit the same thing, i'm going to next page with history.push/ tried also history.replace still getting two or three with same name –  Mar 31 '21 at 13:12
  • Why not use `localStorage`? https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – Dshiz Mar 31 '21 at 13:14
  • know how to add latest 'name' from url to localstorage –  Mar 31 '21 at 13:16

2 Answers2

1

This answer is adopted from HERE.

You should instead encode your names as an array and set it to the name parameter. When you add a new name, use Array.push(ITEM) to add to the end, and to get the most recently added item use Array[Array.length - 1].

//URL to array:
function URLToArray(url, param) {
    return url.substring(url.indexOf(param + '=') + param.length + 1).split('&')[0].split('_');
}

//Array to URL:
function ArrayToURL(array, param) {
  return param + '=' + array.join('_');
}

/*************************************/

//You can then use this as such:

// Get Array
var myArray = URLToArray('https://google.com?name=Bob_Joe_Tom&state=Alaska_Texas_Main', 'name');

console.log(myArray);

// Get URL
myArray.push('Steph'); //Lets add a name to the array
var myNameUrl = 'www.google.com?' + ArrayToURL(myArray, 'name');


console.log(myNameUrl);

I have made this so you can have any number of arrays on the url as well, hence why I have the state value in the example, just to show it can discern between the two arrays.

Jeff B
  • 975
  • 8
  • 25
0

May be this will help you.

function getLatestParamFromUrl(param="") {
  const url = new URL(window.location.href);

  const values = url.searchParams.getAll(param);

  const latestValues = values.length > 0 ? values.pop() : false;

  return !!latestValues && latestValues;
}

console.log(getLatestParamFromUrl("name"));
kunal panchal
  • 798
  • 5
  • 21