React hook can not create inside if codition it will give Error
TotalCounter.js
importReact, { useEffect } from"react";
exportdefaultfunctionTotalCount({ value }) {
if (value !== 0) {
useEffect(() => {
document.title = "Item in basket: " + value;
});
}
return<h1> The totalcount is {value}</h1>;
}
on App.js
return<TotalCount/>;
it will give following error
./src/hooks/TotalCounter.js Line 5:5: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
correct way is following use condition inside the useEffect
importReact, { useEffect } from"react";
exportdefaultfunctionTotalCount({ value }) {
useEffect(() => {
if (value !== 0) {
document.title = "Item in basket: " + value;
}
});
return<h1> The totalcount is {value}</h1>;
}
Then title only update for value != 0
eg : value = 0 // not show title on page
eg: value =5 // show on Title.
You can write Effects inside the functions to,
when create funtions always set name as :useDocumentTitle
TotalCounter.js
importReact, { useEffect } from"react";
exportdefaultfunctionTotalCount({ value }) {
useDocumentTitle("Item in basket:- " + value);
return<h1> The totalcount is {value}</h1>;
}
functionuseDocumentTitle(title) {
useEffect(() => {
document.title = title;
});
}
End of React hooks video
React list and keyshttps://web.microsoftstream.com/video/893c1c4f-5f1d-4f7a-baba-bfbee546dbfb
Event Handles optimization
Basket.js
importReact, { useState } from"react";
importFancyButtonfrom"./FancyButton";
exportdefaultfunctionBasket() {
const [totalCount, setTotalCount] = useState(0);
consthandleChange = (e) => {
if (e.target.value === "i") setTotalCount(totalCount + 1);
elsesetTotalCount(totalCount - 1);
};
const [color, setColor] = useState("red");
consthandleColorToggle = () => {
if (color === "red") setColor("green");
elsesetColor("red");
};
return (
<>
<h1style={{ color }}>Total count is {totalCount}</h1>
UPDATE users SET Fields.modify('insert <string>{sql:variable("@newWebsiteId")}</string> into (//field[@name="Websites"]/ArrayOfString)[1]')
FROM [AdminUsers] users JOIN [AdminUsersRoles] usersRoles ON users.Id = usersRoles.AdminUserId
WHERE usersRoles.AdminRoleId = 'FE0072B6-70AA-4C53-8716-1FD9515E4998' and users.Fields.exist('//field[@name="Websites"]/ArrayOfString/string[text()=sql:variable("@newWebsiteId")]') = 0;
-- create Home page
SET @homePageId = CAST(NewId() AS nvarchar(50))
INSERT [dbo].[FlexiPages] ([Id], [WebsiteId], [Title], [CreatedDate], [ModifiedDate], [Fields], [Url]) VALUES (@homePageId, @newWebsiteId, N'Home', GETDATE(), GETDATE(), N'<FieldsDictionary><field name="MetaDescription" type="Null" /><field name="MetaTitle" type="Null" /><field name="Content" type="Sana.Commerce.Content.ContentBlockCollection, Sana.Commerce"><ContentBlocks><MainBanner><Id>1423653167815</Id><ImagePath>/content/files/images/Homepage-banner.jpg</ImagePath><Link /></MainBanner><Html><Id>87265895-2884-4A2F-92D4-EFE5239D0135</Id><Content><br>This is a Flexi-page. On a Flexi page, you are free to use blocks of text and images, to make the pages look just the way you want them to look. You can easily change the images and text of the Flexi-pages in the “Web pages” section in the Sana Admin. You can also use the In-site editor to change the content of the webstore while looking at it.</Content></Html><ImageTiles><Id>68520105-5903-4D6D-9B72-666AF48435AF</Id><Tiles><ImageTile><ImagePath>/content/files/images/place holder 3.jpg</ImagePath><AltText>Block 1 image</AltText><Link /></ImageTile><ImageTile><ImagePath>/content/files/images/place holder 3.jpg</ImagePath><AltText>Block 2 image</AltText><Link /></ImageTile><ImageTile><ImagePath>/content/files/images/place holder 3.jpg</ImagePath><AltText>Block 3 image</AltText><Link /></ImageTile><ImageTile><Link /></ImageTile></Tiles></ImageTiles></ContentBlocks></field></FieldsDictionary>', N'home')
-- create Customer service page
SET @customerServicePageId = CAST(NewId() AS nvarchar(50))
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis nibh neque, egestas et, aliquet a, fermentum at, nunc. In aliquam. Maecenas metus dui, laoreet in, euismod id, iaculis sit amet, felis. Suspendisse consectetuer odio nec est. Sed blandit mauris vel neque. Pellentesque at orci vitae elit iaculis imperdiet. Sed est turpis, blandit vitae, euismod eget, feugiat ac, arcu.<br />
Duis nisl. Etiam quam ligula, dapibus sed, faucibus eget, volutpat sed, est. Mauris quis sem. Donec iaculis dui fermentum eros. Pellentesque eget libero vitae sapien interdum ullamcorper. Aenean at nulla in velit tristique venenatis. Duis malesuada metus a dolor. Sed ante. Integer mi mi, sodales vitae, adipiscing a, luctus nec, diam.<br />
&nbsp;<br />
Maecenas aliquam aliquet massa. Donec ut purus. Maecenas volutpat, ipsum at consectetuer pretium, urna lorem tempor mi, vitae pellentesque mauris felis eget lorem. Nam ut lectus quis sem placerat venenatis. Nam et nisi non magna pulvinar dignissim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam venenatis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus volutpat. Integer suscipit. Mauris egestas accumsan eros. Nunc et massa. Aliquam erat volutpat.
--------------------------------- When using WebClient-------------------------------------------
ExtendedImageLinkTask
privateStream LoadProductImageStream(IProductImage image)
{
try
{
using (WebClient webClient =newWebClient())
{
// Download from Particular website expects a User-Agent header to be specified.
webClient.Headers["User-Agent"] ="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";
var result = webClient.DownloadData(image.MediumImagePath);
Stream stream =newMemoryStream(result);
return stream;
}
}
catch (Exception ex)
{
TaskLog.Current.Add(this, "Error on image download"+ ex.Message, LogPriority.Medium);
}
returnnull;
}
}
--------------------------------- When use HttpClient-------------------------------------------
using (HttpClient client = new HttpClient())
{
var url = "http://www.te.com/content/dam/te-com/catalog/part/214/184/371/2-1418437-1-t1.jpg/jcr:content/renditions/product-high-res.png";
[HttpPost]
publicActionResult SaveNewOrderTemplate(string name)
{
var existingTemplates =ShopApi.OrderTemplates.GetTemplates();
if (existingTemplates.Any(t => t.Name == name))
{
var orderTemplate_SaveFailedInUse =CommerceFrameworkBase.SanaTexts.GetSanaText("OrderTemplate_SaveFailedInUse");
return Json(new { id =0, error= orderTemplate_SaveFailedInUse }, JsonRequestBehavior.AllowGet);//fail
}
ShopApi.OrderTemplates.SaveOrderTemplate(name);
// Get Template by name var existingTemplates2 =ShopApi.OrderTemplates.GetTemplates();
var template2 = existingTemplates2.Where(x => x.Name == name).FirstOrDefault();
var tempId = template2.Id;
//return Json(tempId, JsonRequestBehavior.AllowGet);//Sucessreturn Json( new { id= tempId }, JsonRequestBehavior.AllowGet);//Sucess
}
// on New Order Template popup Save button click
var btnSave = document.getElementById('OrderTemplate_Save');
if (btnSave !=null) {
btnSave.onclick = savenewordertemplate;
}
function savenewordertemplate() {
var newOrderTemplateName = $("#newOrderTemplateName").val();
$.ajax({
url: Sana.Urls.Home() +'profile/ordertemplates/savenewordertemplate',
method: "POST",
data: { name: newOrderTemplateName }
,
//error: function () {
// alert("Ajax call failed");
//}
}).done(function (data) {
if (data !=null) {
if (data.id ==0) {
var error = data.error;
$("#template_invalid").append(error);
return;
}
var id = data.id;
var retunurl = Sana.Urls.Home() +"profile/ordertemplates/details?templateId="+ id;
window.location.replace(retunurl);
}
})
}
to open popup javascript
var el = document.getElementById('SaveOrderTemplate_test');
if (el !=null) {
el.onclick = openRegisterTerms;
}
function openRegisterTerms() {
Sana.Popup.open('#createOrderTemplatePopup');
}
followig validation will comes when we update content with partial view 2nd time
then we need reset the validation.
//Validattion need to reset after replacing partial view
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
eg: divercy Project,
control.quickorder.js
When a user do a quick search and click add to template button > Partial view data repace > then need to reset the validations
//When Click Add to Template button
$(document).on('click', '.btn-add-to-template', function (event) {
var url = $(".btn-add-to-template").attr('data-src');
var templateId = $('input[name="TemplatePopupForm_TemplateId"]').val();
url = url +"?templateId="+ templateId;
var data = self._getAddedTemplateLines();
var existingData = self._readExistingQuantities();
Sana.UI.LoadingIndicator.show();
return $.ajax({
url: url,
type: 'post',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
// window.location.reload(true);
debugger;
if (data !=null&& data !='') {
if (data.templatePartialView !=null) {
$('.template-replace-area').replaceWith(data.templatePartialView);
}
if ($('.template-replace-area').length ==0) {
$('.template-popup-form').wrap("<div class='template-replace-area'></div>");
}
//When user add new items keep the Previous qty.
self._updateQuantities(existingData);
$(".btn-add-to-template-area").hide();
$(".gvi-template-lines-added > tbody > tr").remove();
$("#AddLinesToBasket").show();
$("#ClearQuantities").show();
Sana.UI.LoadingIndicator.hide();
//Validattion need to reset after replacing partial view
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
Sana.Spinner.init();
}
}
});
});