Home > Mobile >  fecth id and date from url as pros in react js
fecth id and date from url as pros in react js

Time:06-27

This is the url I am getting. I want to access customer id and date from the url to function but because this is not the default class, I am not able to do it and I need help.

http://localhost:3000/update?customer=66&date=2022-06-27&tab=user


const getData = (props) => {
  const config = {
    headers: {
      Authorization: `token `   localStorage.getItem("token"),
    },
  };
  console.log(props.customer);
  return axios
    .get(
      "api?customer="  this.props.customer "&date="   this.props.date,
      config
    )
    .then((res) => res.data)
    .catch((err) => {
      console.error("error ocurred while fetching data", err);
      return null;
    });
};

full code i have given in sandbox for refernce https://codesandbox.io/s/cool-lalande-87jbpq?file=/src/App.js

CodePudding user response:

If you have react-router-dom in your project, you might use useLocation hook

import {useLocation} from 'react-router-dom'
const search = useLocation().search
console.log(URI.parseQuery(search))

CodePudding user response:

I hope this function would be helpful. thanks :)

const url = 'http://localhost:3000/update?customer=66&date=2022-06-27&tab=user'

function getQueryParam(url, parameter) {
  const parameters = new URL(url).searchParams;
  const parameterValue = parameters.get(parameter);
  if (parameterValue === null) {
    return '';
  }
  return parameterValue;
}

console.log(getQueryParam(url, "customer"));
console.log(getQueryParam(url, "date"));

  • Related