How to cancel previous request while searching using axios in Vue 3 composition api (setup) - axios

I want to cancel the previous request while the user is searching or in keyup event, but I didn't find any solution.
btw, I use Pinia store
here is my html code in template
<input type="text" class="w-full h-9 rounded bg-slate-200/50 focus:bg-slate-200 hover:bg-slate-200 pr-9 outline-none pl-2" id="seachDocumentModal"
placeholder="Search document (title or description)" v-model="storeDocument.searchForm.search" #keyup="storeDocument.searchDocument">
here is my code in pinia store
const axios = require('axios').default;
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const searchForm = useForm({
search: null,
program: null,
})
const searchResult = ref(null)
const searchDocument = () => {
if(searchForm.search.replace(/\s/g, '') != ''){
axios.get('/searchDocument/'+searchForm.search, {
cancelToken: source.token
})
.then(res => {
searchResult.value = res.data.documents
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
}
})
}
//source.cancel('canceled')
}
and when I try to search on the input form the previous request is not canceled, and if I remove the comment tag in source.cancel('canceled') this will stop the fetching
this is the result while on keyup
btw I'm new to axios

Related

Redeliver existing form submission to new webhook

I have set up a webhook between salesforce and Typeform and it's working fine. But Typeform has already filled form submissions. Now I want to deliver these responses to a new webhook is there a way to resync existing form submissions?
I dont think this is possible out of the box. You will need to fetch your responses via Typeform Responses API and feed them to your script or webhook.
It looks like the webhook payload is quite similar to the response returned by the API. You can write a script like this to feed all your existing responses from your typeform to a new webhook:
import fetch from 'node-fetch'
import crypto from 'crypto'
import { createClient } from '#typeform/api-client'
const token = process.env.TF_TOKEN // https://developer.typeform.com/get-started/personal-access-token/
const webhookSecret = process.env.SECRET
const uid = process.env.FORM_ID
const typeformAPI = createClient({ token })
const sleep = async (ms) => new Promise(res => setTimeout(res, ms))
// based on https://glitch.com/edit/#!/tf-webhook-receiver
const calculateSignature = (payload) => {
const hash = crypto
.createHmac('sha256', webhookSecret)
.update(payload)
.digest('base64')
return `sha256=${hash}`
}
const feedResponses = (before) => {
typeformAPI.responses.list({ uid, before }).then(async ({ items }) => {
if (items.length > 0) {
// process each response
for (let i=0; i<items.length; i+=1) {
const item = items[i]
const body = JSON.stringify({
"event_id": Date.now(),
"event_type": "form_response",
"form_response": item
})
const response = await fetch('/your-endpoint', {
method: 'POST',
headers: {
'Typeform-Signature': calculateSignature(body)
},
body,
})
const webhookResponse = await response.text()
console.log(webhookResponse)
await sleep(250) // rate-limit the requests
}
// continue with next page of responses
const { token } = items.at(-1)
feedResponses(token)
}
})
}
feedResponses()

Laravel + Vue 3: Upload files with categories

I'm working on uploading multiple files using Laravel and Vue 3. File uploading is doing fine until I added a select tag in the form for the category. I put the category and files into one object so I can pass only 1 parameter. Now in TestController I can get the value of category but giving me error in files.
I need to:
Pass category and files
Read category and files so I can move and save info to database
test.vue
<form #submit.prevent="upload" enctype="multipart/form-data">
<!-- added this tag for category -->
<select v-model="category">
<option v-for="type in categories" :key="type.id" :value="type.id">
{{ type.name }}
</option>
</select>
<input type="file" multiple #change="fileChange">
<button type="submit">Upload</button>
</form>
<script>
import useTest from "../composables/test.js"
import { onMounted } from 'vue'
export default {
setup() {
const { categories, getCategories, uploadFile } = useTest()
onMounted(getCategories)
const attachments = []
const category = 1 // added for category
const upload = async () => {
// const formData = new FormData // without category
// with category, I put inside an object so I can pass only 1 parameter
const form = {
category: category.value,
files: new FormData,
}
// loop to append
Object.keys(attachments).forEach(
// key => formData.append(key, attachments[key]) // without category
key => form.files.append(key, attachments[key]) // with category
)
// call from composable
await uploadFile(form)
}
return {
categories,
category,
upload,
}
},
}
</script>
composable: test.js
import { ref } from 'vue'
import axios from 'axios'
export default function useTest() {
const categories = ref([])
const getCategories = async () => {
let response = await axios.get("/api/fileUpload/")
categories.value = response.data.categories
}
const uploadFile = async (form) => {
// METHOD IS INSIDE TRY CATCH BLOCK
const config = {headers: { 'content-type': 'multipart/form-data' }}
// let response = await axios.post("/api/fileUpload/", form, config)
let response = await axios.post("/api/fileUpload/", form)
console.log(response);
}
return {
categories,
getCategories,
uploadFile,
}
}
TestController
public function store(Request $request)
{
// $uploadFiles = $request; // without category
$uploadFiles = $request['files']; // with category
$uploadFiles = $request['category'];
error_log($uploadFiles);
// error here: Attempt to read property \"files\" on array
foreach ($uploadFiles->file as $file) {
error_log('here');
error_log($file->getClientOriginalName());
error_log($file->getClientOriginalExtension());
error_log($file->getSize());
error_log($file->getMimeType());
error_log(date("m/d/Y H:i:s.",filemtime($file)));
error_log('---------------------');
}
return response()->json(['status'=>'success'], status: 200);
}

disabled submit button after submitting form data to server. in react native

I am new to react native. I have created a form from where I am sending some data to server. Now I want that to disabled submit button after user click on submit . once user submit data then after He unable to send data. means I want to avoid duplicate entry. please help. thanks. if possible also tell how to do it with functional component too.
here is my code
export default function Add(props) {
const { navigation } = props
const offset = (Platform.OS === 'android') ? -200 : 0;
const [AmazonError, setAmazonError] = useState([]);
const [Amazon, setAmazon] = useState('');
const [AmazonCNError, setAmazonCNError] = useState([]);
const [AmazonCN, setAmazonCN] = useState('');
const [AEPSError, setAEPSError] = useState([]);
const [AEPS, setAEPS] = useState('');
const [DMTError, setDMTError] = useState([]);
const [DMT, setDMT] = useState('');
const [BBPSError, setBBPSError] = useState([]);
const [BBPS, setBBPS] = useState('');
const [leadTagNumber, setLeadTagNumber] = useState([]);
const validateInputs = () => {
if (!Amazon.trim()) {
setAmazonError('Please Fill The Input')
return;
}
if (!AmazonCN.trim()) {
setAmazonCNError('Please Fill The Input')
return;
}
if (!AEPS.trim()) {
setAEPSError('Please Fill The Input')
return;
}
if (!DMT.trim()) {
setDMTError('Please Fill The Input')
return;
}
if (!BBPS.trim()) {
setBBPSError('Please Fill The Input')
return;
}
else
{
//+++++++++++++++++++++++++++++++++=submitting form data to api start+++++++++++++++++++++++++++++++++++
{
const leadTagNumber = props.route.params.leadTagNumber
AsyncStorage.multiGet(["application_id", "created_by",'leadTagNumber']).then(response => {
// console.log(response[0][0]) // Key1
console.log(response[0][1]) // Value1
// console.log(response[1][0]) // Key2
console.log(response[1][1]) // Value2
console.log(leadTagNumber)
fetch('https://xyxtech/Android_API_CI/uploaddata/tbservice_details', {
method: 'POST',
headers: {'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" },
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify([{ data}])
})
.then((returnValue) => returnValue.json())
.then(function(response) {
console.log(response)
Alert.alert("File uploaded");
return response.json();
});
});
// event.preventDefault();
}
//+++++++++++++++++++++++++++++++++submitting form data to api end++++++++++++++++++++++++++++++++++++++
Alert.alert("success")
return;
//}
}
};
const handleAmazon = (text) => {
setAmazonError('')
setAmazon(text)
}
const handleAmazonCN= (text) => {
setAmazonCNError('')
setAmazonCN(text)
}
const handleAEPS= (text) => {
setAEPSError('')
setAEPS(text)
}
const handleDMT = (text) => {
setDMTError('')
setDMT(text)
}
const handleBBPS = (text) => {
setBBPSError('')
setBBPS(text)
}
return (
<View style={{flex: 1}}>
<ScrollView style={{flex: 1,}} showsVerticalScrollIndicator={false}>
<TextInput
maxLength={30}
placeholder="AEPS (Adhar enabled payment system) *"
style={styles.inputStyle}
onChangeText={(text)=>handleAEPS(text)}
defaultValue={AEPS}
value = {AEPS} />
<Text>{AEPSError}</Text>
</ScrollView>
<Button
style={styles.inputStyleB}
title="Submit"
color="#FF8C00"
onPress={() => validateInputs()}
/>
</View>
)
}
Set new state property to enable/disable button
const [disableButton, setDisableButton] = useState(false);
Now in your button component, add disabled property with disableButton state.
<Button
style={styles.inputStyleB}
title="Submit"
color="#FF8C00"
onPress={() => validateInputs()}
disabled={disableButton}
/>
Disable you button before fetching data
setDisableButton(true) //Add this
const leadTagNumber = props.route.params.leadTagNumber
Incase of fetch error or after fetching is complete, enable button again
setDisabledButton(false)

nextjs errors with form handling

I'm learning react and nextjs, the page works perfectly without the integration of a UI library, since i installed react suite my page with the login form doesn't work anymore, it returns me an error: TypeError: Cannot read property 'value 'of undefined
My code is:
import React, { useState } from "react"
import { setCookie, parseCookies } from "nookies"
import { useRouter } from "next/router"
import { Form, FormGroup, FormControl, ControlLabel, HelpBlock, Button, Input } from 'rsuite';
const Login = () => {
// set initial const
const router = useRouter()
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
// handle event submit
const handleSubmit = async (e) => {
e.preventDefault();
// fetch user
const response = await fetch( process.env.urlHeadless + '/api/cockpit/authUser', {
method: "post",
headers: {
"Content-Type": "application/json",
'Cockpit-Token': process.env.loginKey,
},
body: JSON.stringify({
user: username,
password: password
})
})
// if user exists
if (response.ok) {
const loggedUser = await response.json()
// set cookie with api_key
setCookie("", "tokenId", loggedUser._id, {
maxAge: 30 * 24 * 60 * 60,
path: "/"
})
// redirect to dashboard
return (router.push("/dashboard"))
} else if (response.status === 412) {
alert('compila il form')
} else if (response.status === 401) {
alert('credenziali di accesso errate')
}
}
return (
<>
<Form>
<FormGroup>
<ControlLabel>Username</ControlLabel>
<FormControl type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
<HelpBlock>Required</HelpBlock>
</FormGroup>
<FormGroup>
<ControlLabel>Password</ControlLabel>
<FormControl type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</FormGroup>
<FormGroup>
<Button appearance="primary" onClick={handleSubmit}>Submit</Button>
</FormGroup>
</Form>
</>
)
}
// async function
export async function getServerSideProps(context) {
// get cookie value
const cookies = parseCookies(context).token;
// if cookie has value
if (cookies) {
return {
// redirect to dashboard
redirect: {
destination: '/dashboard',
permanent: false,
},
}
}
return { props: {} };
}
export default Login;
I also tried using useRef instead of useState, but it didn't work ... where am I wrong? thank you in advance
Looks like rsuite components might have a different onChange implementation, as described in their docs
onChange (formValue:Object, event:Object) => void Callback fired when data changing
If you want the event, try changing the onChange callback in your code to take the second parameter:
<FormControl
...
onChange={(value, e) => setUsername(e.target.value)}
/>

Using react-select Async with loadOptions and redux-form

I'm using react-select library to display a select box. I'm using Select.Async because I need to pull my options from an API. I use Select with loadOptions and it works during the intial page render. However, I'm also using redux-form which can change the value of a Field dynamically (using change). However, when I change the value of the Field like this, the value of the input does change (and I can verify this), but react-select's loadOptions is never called again (even though I thought it was supposed to be listening to a change of value). My question is, is there a way to dynamicaly call loadOptions every time the input value changes?
Thanks,
Edit: Answered on github here
this.state = {
store: '',
};
this.handleStoreSelect = this.handleStoreSelect.bind(this);
handleStoreSelect = (item) => {
this.setState({
store: item.value
}
};
<Select.Async
name="storeID"
value={this.state.store}
loadOptions={getStores}
onChange={this.handleStoreSelect}
/>
const getStores = () => {
return fetch(
"api to be hit",
{
method: 'get',
headers: {
'Content-Type': 'application/json'
}
}
)
.then(response => {
if(response.status >= 400){
throw new Error("error");
}
return response.json()
})
.then(stores => {
let ret = [];
for(let store of stores) {
ret.push({value: store._id, label: store.name})
}
return {options: ret};
})
.catch(err => {
console.log('could not fetch data');
console.log(err);
return {options: []}
})
};
Using this we can fetch the data and pass this object in the loadoptions.
copy this code outside the class. and also i'm posting the code to be implemented for loadoptions
It might be a better solution than this, but a quick one is to set a ref to your Select.Async component, and when a change action is triggered (like the change of an input - your case, or one button click event - like in the code below) you can update its options. I'm using a similar example with the example of their docs.
class YourClass extends React.Component {
getOptions = (input, callback) => {
setTimeout(function () {
callback(null, {
options: [
{value: 'one', label: 'One'},
{value: 'two', label: 'Two'}
]
});
}, 500);
};
updateOptions = () => {
this.selectAsync.state.options.push(
{value: 'three', label: 'Three'}
)
}
render() {
let props = this.props;
return (
<div>
<Select.Async
ref={selectAsync => this.selectAsync = selectAsync}
loadOptions={this.getOptions}
/>
<button onClick={this.updateOptions}>
Load more items
</button>
</div>
)
}
}