React JS NAN 'new URLSearchParams(this.props.location.search)'

297 Views Asked by At

I'm trying to recuperate URLSearchParams(props.location.search) with params in text format but i only succes to recuperate the params with numbers.
ex = {id:1, name:'Adrien', age:23} => result {id:1, name:Nan, age:23}

My code : 

Home.js 

let Home = (props) => {
let state = {
id: 1,
name: 'Sfafa',
age: 34,
};

let param = [];
for (let i in state) {
param.push(encodeURIComponent(i) + '=' + encodeURIComponent(state[i]));}

let query = param.join('&');

CreatPost.js :

class CreatePost extends Component {
constructor(props) {
super(props);
this.state = {
perso: {
id: '',
age: '',
name: '',
},
};
}
getData = () => {
let params = {};
let query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
params[param[0]] = +param[1];
**console.log(params);**
}
this.setState({
perso: params,
});
};

**My problem :** 
for the console.log(params) => 
id: 1
**name: NaN** (how can i recuperate the text-format ? ) 
age: 34

Thank you !
1

There are 1 best solutions below

0
On

You convert all your values to numbers by +param[1]. You are able to do it later, like:

params[param[0]] = param[1]; // no "+", all values are strings
this.setState({
  perso: {
    id: Number(params.id),
    name: params.name,
  },
});

Or if you wish to have universal method to parse your params, you can do something like this:

const [key, value] = param;
const parsedValue = Number(value);
params[key] = isNaN(parsedValue) ? value : parsedValue;