Is it possible to hook our own custom AI model to the Trengo Flowbot? Or use any of their APIs/webhooks to achieve the same?
The chat widget is already provided by Trengo, but we need to integrate our own responses into it from an in-house generated AI model
Category: javascript
Category Added in a WPeMatico Campaign
Next.js 13 navigation router refresh preserves state
I have this below component and it’s included withing a Server Component that fetches data and render it. As it can be seen I call router.refresh()
on click so it will rerun that page and refetch the data. And it does but the problem is Nextjs keep preserving this state, so when i call setRefreshing(true)
even though server component rerun refreshing state is still true.
'use client'
import { useRouter } from 'next/navigation'
import Button from './Button'
export default function Refresh() {
const [refreshing, setRefreshing] = useState(false)
const router = useRouter()
const handleClick = () => {
setRefreshing(true)
router.refresh()
}
return (
<Button onClick={handleClick}>
<i className={`bi bi-arrow-repeat text-lg ${refreshing ? 'animate-spin' : ''}`}></i>
Refresh
</Button>
)
}
useEffect
is also not running after refresh so i can’t set it to false in there either. I’ve found a workaround to pass an array prop to the component which then it will rerun useEffect(() => {...}, [serverHackyProp])
.
<Refresh inProgress={[false]} />
const [[refreshing], setRefreshing] = useState(inProgress)
const router = useRouter()
useEffect(() => {
setRefreshing(inProgress)
}, [inProgress])
const handleClick = () => {
setRefreshing([true])
router.refresh()
}
It works because passed array will always have a new reference so useEffect will run every time server rerun. But I don’t like to do that unless it’s my last choice but i couldn’t find a way to setRefreshing(false)
after router refreshed (server refetched).
isFieldsTouched turn “true” when use setFieldsValue antd form
I want to check user type in form with isFieldsTouched but when the first render, i fill data to the form and isFieldsTouched turn to “true”, even i’m not touch at all. How can I fix this.
My version:
antd:4.21.5,
react:18.2.0
demo:here
I want isFieldsTouched false when I setFieldsValue. Anyone have solution. Thank alot
LIFF App – liff init getting TypeError: Failed to fetch at e.apply
Here is the link to my app scanqr.termn.repl.co
Open the app in the browser is totally fine but when I tried openning the app in Line app, it works in the first time. I keep getting TypeError: Failed to fetch at e.apply
I tried looking around for this specific error but could not find anything.
Functions running simultaneously, but should run one after another
I have created three functions, used async await and while calling, chained them using .then
, but it is not working and all the three functions are running on the same time, but they should run one after another. So basically first func
should run, after it has ended, then func2
should run followed by the third function.
Code:
const array = useRef([]);
useEffect(() => {
const func = async () => {
if (startElement.i && startElement.j) {
await startVisiting(
grid[startElement.i][startElement.j],
grid[startElement.i][startElement.j]
);
}
return 0;
};
const func2 = async () => {
var element = endElement;
while (element != startElement) {
if (element) if (element.i && element.j) array.current.push(element);
element = element.parent;
}
console.log(array);
};
if (startElement.i) {
func()
.then(func2())
.then(async () => {
console.log(array);
if (array[0])
if (array[0].i && array[0].j && array[0].visited) {
array.forEach((el) => {
grid[el.i][el.j]["way"] = true;
});
console.log("hoo");
setStartElement(startElement);
}
})
.then(() => {
console.log(array);
});
}
}, [startElement]);
Also in the func2
I have not used await anywhere, still if I am removing the async
it is throwing an error.
Displaying h1 dynamically on a template page
I’d like to know how to dynamically display the h1 title of a page in a text displayed on a form.
Let’s say I have an events site with 10 pages, each dealing with a separate event. On these 10 pages, there’s a contact form that’s the same, because for obvious reasons I can’t create a form for each page. I’d like to display the page’s h1 title on this form to personalize the form. This way, for each page, on the same form, the title would be different.
Similarly, so that internally I can know which form sent corresponds to which page, I’d like to be able to add this same functionality inside the form (Contact Form 7). For example, if a user selects Christmas as the event, he fills in the form, which is the same for all ten pages, but I need to be able to know that the form comes from the Christmas page, hence the usefulness of retrieving the h1 dynamically.
I’m using WordPress with a paid theme. Any ideas? Thanks in advance!
MUI date picker wont show dates before 1900
i want a datepicker that allows the user to set dates from 1850s, but in the mui datepicker starts from 1900s.
ive recreated the issue in this codesandbox
im using mui in the rest of the project, so i really dont wanna switch to another package, also i’ve tried replacing momentjs with datefns and dayjs to no avail
Why is there a diffrence in using for(var i = 3; i >= 0; i–) and for(var i = 3; i–;) in Javascript
Why is there a big diffrence in using for loop with and without constraints.
With condition
for(var i = 3; i >= 0; i--) { console.log(i); }
outputs
3
2
1
0
Without condition
for(var i = 3; i--;) { console.log(i); }
outputs
2
1
0
Why does the one without condition skip the first iteration and also stop at 0.
If you use no condition but add one instead of subtract it will result in an infinite loop
FireBase once method behaves recursively
I have a dailog element and a function for it to get all comments and add them to comment section and a input with button to add a new comment
But when I click on button it recursively adds the comment unless I close browser
Html
<dialog id="reply">
<div id="replymain">
<button id="replyclose">×</button>
<div id="coms">
<div id="com">hello there</div>
</div>
<div id="send">
<input id="sendinput" placeholder="Message" />
<button id="sendreply">+</button>
</div>
</div>
</dialog>
For adding all the comments
function comment(id){
localStorage.setItem("last",id)
reply.showModal()
firebase.database().ref("memes/" + id).once("value",(snap) => {
const cs = snap.val().comments || []
console.log(cs)
cs.forEach(c => {
coms.innerHTML += `
<div id="com">${c}</div>
`
})
})
}
Button function
sendreply.onclick = () => {
addC(localStorage.getItem("last") , sendinput.value , true)
}
AddC function
function addC(id,c){
firebase.database().ref("memes/" + id).once("value",(snap) => {
const cs = snap.val().comments || []
firebase.database().ref("memes/" + id).update({
comments: [...cs,c]
})
})
}
is there a way to fix it or do I have to forcefully cancel it with setTineout
stop tag being self-closing solution
I’m looking for a way to stop self-closing tag like
<link rel='stylesheet' />
to
<link re='stylesheet'></link>
.
It’s always become self-closing.
I tried to remove save action in settting.json and add
"react/self-closing-comp": ["error", {
"component": false,
"html": false
}]
into tslint.json
, but it still not working.
imported sdk shows Function and not class inconsole.log
I have imported a sdk as below
import hid from "hs-ssi-sdk";
or,
import {
HypersignDID,
HypersignSchema,
HypersignVerifiableCredential,
HypersignVerifiablePresentation,
} from "hid-ssi-sdk";
when i hover over HypersignDID
it showing (alias) class HypersignDID import HypersignDID
but when i log the value as below
console.log(HypersignDID)
result:-
[Function: HypersignDID]
what is the reason behind it and how to fix it in sdk so that I will get class if it is a class in sdk.
I am using typescript to write sdk code and new in this.
i am not able to reset the react-select dropdown value
<Formik
initialValues={{
keyword: ”,
requestNo: ”,
problemName: ”,
reciverName: ”,
divisionName: ”,
departmentName: ”,
startDate: ”,
endDate: ”,
status: ”,
}}
onSubmit={async (values, actions) => {
if (
postDate === ” &&
expireDate === ” &&
values.requestNo === ” &&
values.problemName === ” &&
values.reciverName === ” &&
values.departmentName === ” &&
values.divisionName === ” &&
values.status === ”
) {
await Swal.fire({
title: ‘Error’,
text: ‘Please select atleast one field’,
icon: ‘error’,
confirmButtonText: ‘OK’,
})
return
}
console.log(‘valuessss’, values + ” + dateRange)
setFormValues(values)
setisLoading(true)
setIsButtonDisabled(true)
try {
const filterBy = [
‘requestNo’,
‘reciverName’,
‘problemName’,
‘divisionName’,
‘departmentName’,
‘startDate’,
‘endDate’,
‘status’,
‘search’,
]
const pDate = postDate === ” ? ” : new Date(postDate).toISOString()
const eDate = expireDate === ” ? ” : new Date(expireDate).toISOString()
console.log(‘pDate ‘, pDate + ” + eDate)
const filterValue = [
values.requestNo,
values.reciverName,
values?.problemName,
values?.divisionName,
values?.departmentName,
pDate,
eDate,
values?.status,
MUTsearchKnowledge,
]
const response = await axios.get(
`${process.env.REACT_APP_API_URL}knowledgesearch/get-data`,
{
params: {
filterBy: filterBy.join(','),
filterValue: filterValue.join(','),
page: numofPages - 1,
size: pageSize,
sortColumn: sortColumn,
isAscending: isAscending,
},
headers: {
'content-type': 'application/json',
},
}
)
const result = await response.data
setisLoading(false)
setGetKnowledgeSearchData(result.KnowledgeSearch)
settotalUsers(result?.total)
setIsButtonDisabled(false)
console.log(
'Knowledge search get data successfully ==> KnowledgeSearchListTable_getKnowledgeData',
result
)
} catch (error) {
console.log(
'Knowledge search get data failed ==> KnowledgeSearchListTable_getKnowledgeData',
error
)
}
setShowResult(true)
}}
>
{(props) => {
const {
values,
touched,
errors,
handleChange,
handleBlur,
handleReset,
handleSubmit,
setFieldValue,
resetForm,
} = props
return (
<div className='card mb-12'>
<div className='card-body flex-column p-5'>
<div className='fv-row border p-10'>
<div className='col-lg-12'>
<form onSubmit={handleSubmit} onReset={handleReset}>
<div className='row'>
<div className='col-lg-4 fv-row mb-5'>
<label className='form-label'>{requestNoLabel?.value}</label>
<Field
name='requestNo'
className='form-control form-control-md form-control-solid'
placeholder={requestNoLabel?.value}
/>
</div>
<div className='col-lg-4 fv-row mb-5'>
<label className='form-label'>{problemNameLabel?.value}</label>
<Field
name='problemName'
className='form-control form-control-md form-control-solid'
placeholder={problemNameLabel?.value}
/>
</div>
<div className='col-lg-4 fv-row mb-5'>
<label className='form-label'>{receiverNameLabel?.value}</label>
<Field
name='reciverName'
className='form-control form-control-md form-control-solid'
placeholder={receiverNameLabel?.value}
/>
</div>
<div className='col-lg-4 fv-row mb-5'>
<label className='form-label'>{departmentLabel?.value}</label>
<Field
name='departmentName'
id='departmentName'
render={({field, form}: {field: any; form: any}) => (
<Select
{...field}
options={[{ label: intl.formatMessage({id: 'GENERIC.SELECT'}), value: '' }, ...departmentOptions]}
placeholder={intl.formatMessage({id: 'GENERIC.SELECT'})}
styles={selectStyles}
isClearable
onChange={(selectedOption: any) => {
form.setFieldValue('departmentName', selectedOption?.value)
}}
value={departmentOptions?.find(
(option) => option?.value === form.values.departmentName || null
)}
/>
)}
/>
</div>
<div className='col-lg-12 fv-row mt-8 text-end'>
<button
type='submit'
className='btn btn-primary me-3'
disabled={isButtonDisabled}
>
{isButtonDisabled ? processingLabel?.value : searchLabel?.value}
</button>
<button
type='reset'
className='btn btn-light-primary'
onClick={() => {
props.handleReset()
setShowResult(false)
setDateRange('')
setFieldValue('departmentName', '')
resetForm()
}}
>
{clearLabel?.value}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
)
}}
</Formik>
i want to reset the value when i will click on clear button but the selected value in the react-select is not clearing.I have tried many solutions but it is not working.Can anyone help me , how can i reset the value of react-select dropdown when click on clear button?
Javascript in react causes website to collapse when the page reloads
I wrote Javascript to create a toggle button from an image to pop out a full-screen navigation bar.
Javascript
const menuHamburger = document.querySelector(".menu-hamburger")
const navLinks = document.querySelector(".nav-links")
menuHamburger.addEventListener('click',()=>{
navLinks.classList.toggle('mobile-menu')
})
This was placed in after all the imports of the react main app.js file
What this does is it removes the margin left:-100% that was set in the nav links (vertical navigation bar) to make it appear by adding a class of margin:0 in media queries.
This is the navigation bar css.
.nav-links{
position:absolute; Applied to 3 Li elements.
background-color:rgba(255, 255, 255, 0.2);
backdrop-filter: blur(8px);
width:100%;
top:0;
left:0;
justify-content:center;
align-items:center;
display:flex;
margin-left:-100%;
transition: all 0.5s ease;
height:100vh;
}
Though it works when I reload the page it removes all the elements in the body.
Also the blurry vertical navigation bar is supposed to blur all the elements however some text are very clear.
If this is not enough Code Sandbox.
Adding on, the code shows no errors though everything is missing.
I expect to have a blurry navigation bar that blurs all the elements.
I tried removing the Javascript from the website and it was full functional but when I put it back it disappears.
How do I include an HTML tag with its attributes as a string inside an element?
I want to include this html tag with those exact colors inside an element inside a JSX environment.
I tried doing it like this:
const htmlTag = '<ifx-icon icon="calendar-16"></ifx-icon>';
and then I render it inside an element <div>{htmlTag}</div>
and this works, but how do I now select the various parts of the string? How do I select <ifx-icon>
, icon
etc in order to color it differently?
Any other ideas?
How to send outbound media message (pdf) in twilio using template
I want to send transactional notice pdf messages whatsapp that too outbound. I read docs and found out, it is done using using content api.
I wanted to send something like
enter image description here
so the template i have created looks like this
enter image description here
so when i am sending the media message using this template
client.messages
.create({
from: 'MGXXXXXXXXXXX',
contentSid: 'HXXXXXXXXXXX',
contentVariables: JSON.stringify({
1: 'Kushagra Agrawal',
2: 'Mon Jun 19 2023 10:10:54 GMT+0000 (Coordinated Universal Time)',
3: 'attachment.pdf?alt=media&token=XXXXXXXXXXXX'
}),
to: 'whatsapp:+91mynumber'
})
.then(message => console.log(message.sid));
the code is running fine and giving me sid but i am not recieving the message.
I tried sending direct using mediaURL but as expected that also did not work.