React-URLSearchParams returning Null object - reactjs

I am using the following code to retrieve query parameters from URL but URLSearchParams returns an empty object.
PS: uselocation.search returning correct output.
const stringdata = useLocation().search
const queryparameter = new URLSearchParams(stringdata)
console.log("query parameter :", queryparameter)
const query = queryparameter.get('q');
var url_string = `http://localhost:3000/recipes${query}`

You can try using window.location.search over user search params.
That should look something like:
const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;

The search property returns the querystring part of a URL, including the question mark (?).
const queryParams = new URLSearchParams(window.location.search);
Then you need to check if queryparameter.get('q') exists, otherwise it will return null and will append null to url.
let query;
if(queryParameter.has('q')){
query = queryparameter.get('q');
}
then
var url_string = `http://localhost:3000/recipes/${query}`

Related

How to Query By Firebase Timestamp (from - to)?

i want to query my data by time stamp
let date = new Date();
var today = new Date();
var yesterday = date.setDate(today.getDate() - 1);
console.log(date)
const dataTable = collection(db, 'sales')
let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)
console.log(qSnap)
error : Uncaught (in promise) FirebaseError: Expected type 'mc', but it was: a custom xh object
The error that you encountered was produced by not using the query() method as pointed out by #AyseAsude. Now, after fixing the query, you should also convert the variable yesterday into a date format and iterate the items from the query. See code below:
let date = new Date();
var today = new Date();
var yesterday = new Date(date.setDate(today.getDate() - 1));
const dataTable = collection(db, 'sales')
let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)
qSnap.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
For more information, you check out this documentation.
You should use the query function and create Query instance.
import {query} from "firebase/firestore";
let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)
Documentations to refer to:
https://firebase.google.com/docs/firestore/query-data/queries#simple_queries
https://firebase.google.com/docs/reference/js/firestore_#query

Efficient way to use display the results from the fetch?

I am started learning reactjs. I have fetch result from the given API https://lichess.org/api/user/nihalsarin2004 which shows the profile of Lichess User. (Here nihalsarin2004). But for using every detail, I have coded them as below:
let fName = JSON.stringify(data?.profile?.firstName);
let lName = JSON.stringify(data?.profile?.lastName);
let totalGames = JSON.stringify(data?.count?.all);
let totalWins = JSON.stringify(data?.count?.win);
let totalDraws = JSON.stringify(data?.count?.draw);
let totalLoss = JSON.stringify(data?.count?.loss);
let userLink = JSON.stringify(data?.url);
.
.
.
.
.
let blitzRating = JSON.stringify(data?.perfs?.blitz?.rating);
let bulletRating = JSON.stringify(data?.perfs?.bullet?.rating);
let rapidRating = JSON.stringify(data?.perfs?.rapid?.rating);
let classicalRating = JSON.stringify(data?.perfs?.classical?.rating);
let chess960Rating = JSON.stringify(data?.perfs?.chess960?.rating);
let antichessRating = JSON.stringify(data?.perfs?.antichess?.rating);
let checkRating = JSON.stringify(data?.perfs?.threeCheck?.rating);
let atomicRating = JSON.stringify(data?.perfs?.atomic?.rating);
let hordeRating = JSON.stringify(data?.perfs?.horde?.rating);
And then using these variables in react components ?
Do we any alternative for this ?
Use Destructuring Assignment and assign a new variable names in the destructuring:
let { firstName: fName, lastName: lName } = data?.profile;
let { all: totalGames, win: totalWins /* and so on */ } = data?.count;
You can de-structure them as follows:
if(!data.profile){
// check if there is data and profile
// same for other keys in data obj
return null
}
let {firstName, lastName} = data.profile
let {all,win, draw, loss} = data.count
// so on...
Note: whenever you are de-structuring any variable from an object make sure you name that variable same as key that you want to extract
for example:
let obj={
name:"John",
age:20,
}
// if you want to destructure obj you can do following
let {name, age}=obj
//variable names in {} should be same as key in obj

Queried parameter is null

I'm trying to query the pid parameter of my http://localhost:3000/edit-product?pid=Z4HLrHGZ1ikKIwlEVkM6 URL.
Here is my code:
const params = new URLSearchParams(window.location.path);
const pid = params.get("pid");
console.log("This----->", pid);
Each time I run the code, the console prints that the pid value is null
Any ideas what I'm doing wrong?
You should be using window.location.search. window.location.path is undefined.
MDN: URLSearchParams#Examples
Gotchas
The URLSearchParams constructor does not parse full URLs.
However, it will strip an initial leading ? off of a string, if
present.
var paramsString1 = "http://example.com/search?query=%40";
var searchParams1 = new URLSearchParams(paramsString1);
searchParams1.has("query"); // false
searchParams1.has("http://example.com/search?query"); // true
searchParams1.get("query"); // null
searchParams1.get("http://example.com/search?query"); // "#" (equivalent to decodeURIComponent('%40'))
var paramsString2 = "?query=value";
var searchParams2 = new URLSearchParams(paramsString2);
searchParams2.has("query"); // true
var url = new URL("http://example.com/search?query=%40");
var searchParams3 = new URLSearchParams(url.search);
searchParams3.has("query") // true

Angularjs print value in localstorage

Angularjs how to print name in localstorage
i try this console.log($scope.storageData.name); //output is Undifiend
var user = angular.toJson(response.data.user);
localStorage.setItem('user', user);
$rootScope.authenticated = true;
$scope.storageData = localStorage.getItem("user");
console.log($scope.storageData);
console.log($scope.storageData.name);
output
{"id":20,"name":"test","email":"test#gmail.com","roles":"","created_at":"2018-02-27 10:07:53","updated_at":"2018-03-02 06:51:26"}
You need to parse it to an object before accessing name
$scope.storageData = JSON.parse(localStorage.getItem("user"));
You need to parse it to an object first. Your this line here:
$scope.storageData = localStorage.getItem( "user" );
Should be changed with this:
$scope.storageData = JSON.parse( localStorage.getItem( "user" ) );

url sharepoint list camlquery

I'm trying to collect my url and the description of the url stored in a column of a list from sharepoint and i don't know how to collect the URL value.
This is my code :
var queryResultSaleListItems = clientContext.LoadQuery(listData);
clientContext.ExecuteQuery();
//Read the Data into the Object
var TipsList = from Tips in queryResultSaleListItems
select Tips;
ObservableCollection<Tips> colTips = new ObservableCollection<Tips>();
//Read Every List Item and Display Data into the DataGrid
foreach (SPSClient.ListItem item in TipsList)
{
var tips = new Tips();
tips.TitleTip = item.FieldValues.Values.ElementAt(1).ToString();
tips.App = item.FieldValues.Values.ElementAt(4).ToString();
//should collect the url
tips.URL = item.FieldValues.Values.ElementAt(5).ToString();
//should collect the description of the url
tips.URLdesc = item.FieldValues.Values.ElementAt(5).ToString();
colTips.Add(tips);
}
ListboxTips.DataContext = colTips;
In my expression its >
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Url
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Description
Thanks for your help,
Use FieldUrlValue for getting hyperlink field in Client Object Model.
Use Following Code:
string server = "siteURL";
var ctx = new ClientContext(server);
var web = ctx.Web;
var list = web.Lists.GetByTitle("CustomList");
var listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(listItemCollection);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in listItemCollection)
{
string acturlURL = ((FieldUrlValue)(listItem["URL"])).Url.ToString(); // get the Hyperlink field URL value
string actdesc = ((FieldUrlValue)(listItem["URL"])).Description.ToString(); // get the Hyperlink field Description value
}

Resources