Javascript fetch method failing - javascript

So I am trying to call an api using the javascript fetch method. But it keeps failing.
I am trying to call this api this way:
const addressReq = await fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:{
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
}
}).then(async(res) => {
console.log(await res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))
But it doesn't work. I keep getting a 400 error
Object {
"error": "Bad Request",
"message": Array [
"applicant should not be null or undefined",
"state should not be empty",
"state must be a string",
"street should not be empty",
"street must be a string",
"lga should not be empty",
"lga must be a string",
],
"statusCode": 400,
}
But when I use postman it works.
I have also added a webhook on pipedream and I do not receive that either to prove it doesn't work.
I have tried everything possible but no positive feedback. Is there any thing I'm doing wrong?

Thanks to #Barmar all I needed to do was add JSON.stringify()
Outcome:
const addressReq = fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:JSON.stringify({
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
})
}).then((res) => {
console.log(res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))

You don't have to use asynch and await here, removed them, try again, should work
const addressReq = fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:{
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
}
}).then((res) => {
console.log(res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))

Related

Why do I get a blank page when I click on my textarea zone with react-wysiwyg?

After getting the API response inside MenuItemDetail, I set it to the responses state, which is then passed down to Tabs, then TabContent. Here, I want to read correctly its resp and name props then display whatever they contain in the two corresponding editors i.e respEditor and nameEditor (resp and name fields in my json from API).
I can retrieve my resp and name from my API, but when I try to click on the textarea zone in order to add or modify the content I got a blank page, and get this error in the console:
Uncaught TypeError: contentState.getBlockMap is not a function
i've check this question on the forum : DraftJS - contentState.getBlockMap is not a function
I really really don't know why
const TabContent = ({ onChange, resp, , status }) => {
const [respEditor, setRespEditor] = useState(
EditorState.createWithContent(convertFromHTML(resp !== null ? resp : ""))
);
function respChange(state) {
setRespEditor(state);
onChange({
resp: convertToRaw(state.getCurrentContent()),
status
});
}
let handle = async (e) => {
e.preventDefault();
try {
let res = await fetch("", {
method: "POST",
body: JSON.stringify({
resp: convertToHTML(respEditor.getCurrentContent()),
status: status
})
});
} catch (err) {
console.log(err);
}
};
return (
<form onSubmit={handle}>
<Editor
editorState={respEditor}
onEditorStateChange={respChange}
wrapperclassName="wrapperclassName"
editorclassName="editorclassName"
toolbar={{
options: ["inline"],
inline: { inDropdown: false }
}}
/>
<input
type="radio"
value="B"
onChange={(e) =>
onChange({
resp,
status: e.target.value
})
}
<input
</span>
</div>
</form>
);
};
Here is my json from api for menuId:1:
[
{
"menuId": 1,
"name": "Menu1",
"trust":1,
"dishes": {
"meat": "N/A",
"vegetables": "pea"
},
"list": [
{
"resp": "resp1",
"question": "question1",
"link": "",
"name": "Name1",
"status": "Finished"
},
{
"resp": "resp2",
"question": "question2",
"link": "http://mylink.com",
"name": "Name2",
"status": "Saved"
}
]
}
]
Solution Codesanbox: https://codesandbox.io/s/react-wysiwyg-draft-js-ecmpth?file=/src/TabContent.js
Edited
You can use convertFromHTML from draft-convert to parse HTML string to EditorContent. Install draft-convert, which is the recommended way in the official example. (reference: https://stackoverflow.com/a/36904924/9744063)
npm install draft-convert
import { convertFromHTML } from ‘draft-convert’;
const [respState, setRespState] = useState(EditorState.createWithContent(convertFromHTML(resp)));
const [nameState, setNameState] = useState(EditorState.createWithContent(convertFromHTML(name)));

Using bootstrap vue pagination how to make an axios call for each page?

Reference https://bootstrap-vue.org/docs/components/pagination
data() {
return {
currentPage: 1,
}
computed: {
rows() {
return this.productsList.length;
},
methods() {
layoutchange() {
this.layout = !this.layout;
if (this.layout === true) {
this.listProducts();
} else {
this.gridProducts();
}
},
gridProducts() {
let project_key = 'https://.....url'
const categoryUrl = project_key + '/................offset=0&limit=12';
const sendGetRequest = async() => {
let access_token = await axios.request({
method: "get",
baseURL: categoryUrl,
headers: {
'Authorization': "Bearer " + accToken,
'Content-Type': 'application/json',
},
data: {}
}).then((response) => {
if (response) {
// this.productsList = response.body;
this.productsList = response.data.results;
// eslint-disable-next-line
console.log(this.productsList);
}
});
};
sendGetRequest();
}
listProducts() {
let project_key = 'https://.....url'
const categoryUrl = project_key + '/................offset=0&limit=8';
const sendGetRequest = async() => {
let access_token = await axios.request({
method: "get",
baseURL: categoryUrl,
headers: {
'Authorization': "Bearer " + accToken,
'Content-Type': 'application/json',
},
data: {}
}).then((response) => {
if (response) {
// this.productsList = response.body;
this.productsList = response.data.results;
// eslint-disable-next-line
console.log(this.productsList);
}
});
};
sendGetRequest();
}
<ul v-if="layout == true">
<div class="listview-plp" v-for="product in productsList" :key="product.key" id="product" :items="productsList" :current-page="currentPage">
<div class="da">sdds</div>
<b-pagination v-model="currentPage" :total-rows="rows" #change="handlePageChange"></b-pagination>
</ul>
<ul v-if="layout == false">
<div class="listview-plp" v-for="product in productsList" :key="product.key" id="product" :items="productsList" :current-page="currentPage">
<div class="da">sdds</div>
<b-pagination v-model="currentPage" :total-rows="rows" #change="handlePageChange"></b-pagination>
</ul>
I am working on pagination for grid and list view in vuejs, the problem here is i want to display pagination for both like if it is grid view-(12 items per page) and if it is list view(8 items per page), All this i am getting from an api with offset and limit values, So i need to call an API for each page. to get it work. So i am not sure how to call api for each page using and to handle in for loop so (in my case layoutchange() method)
in grid view page1 (offset0, limit 12) page2-(offset12, limit 24) page3 (offset24 limit 36)....
in list view page1 (offset0, limit 8) page2-(offset8, limit 16) page3 (offset16 limit 24)....
Below i have taken two methods and called an api inside it like gridProducts and listProducts.(where the api is working fine with 12 and 8 items) initially.
So please help me with, Calling an api per each page using b-pagination, simultaneously using for loop for grid and list view

Ajax to php retrieving formdata

I'm sending my files through vue.js to my laravel backend but I'm not able to retrieve the data correctly.
Vue.js :
<b-form-file
v-model="files"
:state="Boolean(files)"
placeholder="Choisissez un fichier..."
drop-placeholder="Glisser ici..."
multiple
accept=".jpg, .png"
class="textOverflow"
name="file[]"
></b-form-file>
Ajax :
onSubmit(){
let formData = new FormData();
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
formData.append("filePos: "+ i, file, this.id);
}
axios.post('/pictures', formData,
{headers: {'Content-Type': 'multipart/form-data'} })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Laravel php :
public function store(Request $request)
{
$images = $request->all();
info($images);
}
So this gives me :
[2020-04-26 15:40:48] local.INFO: array (
'filePos:_0' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => '25',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
[2020-04-26 15:40:50] local.INFO: array (
'filePos:_0' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => '25',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
Which is perfect, but I can't retrieve specific data like if I just want the originalName and do ->request('name'), I can the weird chain of characters as if I wasn't the correct encoding.
Does someone know how to retrieve specific information for separating the images, manipulate them and so.
Thanks for reading
Edit :
If I use dd instead of info :
array:1 [
"filePos:_0" => Illuminate\Http\UploadedFile {#343
-test: false
-originalName: "25"
-mimeType: "image/png"
-error: 0
#hashName: null
path: "C:\Users\Gian\AppData\Local\Temp"
filename: "phpEC28.tmp"
basename: "phpEC28.tmp"
pathname: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
extension: "tmp"
realPath: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
aTime: 2020-04-26 16:28:39
mTime: 2020-04-26 16:28:39
cTime: 2020-04-26 16:28:39
inode: 35184372088948345
size: 109758
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
}
]

Unable to show value in Template

I have successfully retrieved the JSON data but I don't seem to find a way to output the value as I would be able to for others. Wonder what went wrong in the way to display the value in my template?
The function is as follows,
getUserInfo() {
var service = this;
let url = service.appConfig.Shop_URL + "/wp-json/wp/v2/users/" + service.userService.id;
url = this.initUrl(url, '');
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + service.userService.token);
headers.append('Content-Type', 'application/json');
return new Promise(function (resolve, reject) {
service.http.get(url, { headers: headers }).pipe(map(res => res.json())).subscribe(data => {
if (data) {
service.cachedData = data;
console.log(data);
resolve(service.cachedData);
}
else {
reject();
}
});
});
}
listUserDetails() {
this.getUserInfo().then((data: Array<any>) => {
this.user_details = data;
console.log(this.user_details);
});
}
In the console the data shows as follows,
{id: 584, name: "test", url: "", description: "", link: "https://oc.xxxxx.com/author/test/", …}
avatar_urls: {24: "https://secure.gravatar.com/avatar/b642b4xxx", 48: "https://secure.gravatar.com/avatar/b642b4xxx", 96: "https://secure.gravatar.com/avatar/b642bxxxx"}
commission_earned: "36"
commission_rate: "5"
daily_sales: "720"
description: ""
id: 584
link: "https://oc.xxxxx.com/author/test/"
meta: []
name: "test"
slug: "test"
url: ""
And in my template I used the following method but it is not returning the values.
<span *ngFor="let detail of user_details">{{detail.daily_sales}}</span>
thanks in advance.
You proberly just need to handle the user_details like an object not an array
so change
<span *ngFor="let detail of user_details">{{detail.daily_sales}}</span>
to
<span >{{user_details.daily_sales}}</span>
More info on *ngFor here : https://angular.io/api/common/NgForOf

Can not delete post's comment reactively in Vue.js

In my blog-like Vue.js app, the posts are rendered in a v-for loop. When a button under each post is clicked, its comments are fetched from the server and attributed like this, as post objects have no comments attribute:
`this.$set(post, 'comments', res.data.comments) ;`
The code to render the comments is this:
<div v-for="(c, j) in post.comments" :key="j">
<span>{{c.body}}</span>
<span v-if="post.user_id==userId" #click="delComment(c, post)">Delete me!</span>
</div>
And the deleteing method:
delComment(c, post) {
const payload = {
token: this.token,
cid: c.id
}
axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
.then( (res)=> {
post.comments = this.post.comments.filter((comment)=>{
return comment.id != c.id
});
this.$set(post, 'comments', post.comments) ;
})
.catch( error => {
console.log(error);
});
},
But when I click the Delete link, I get this error in the console:
TypeError: Cannot read property 'comments' of undefined
at eval (Home.vue?76f2:540)
How can I fix this?
You're missing this before post :
//v-------------//here
this.post.comments = this.post.comments.filter((comment)=>{
return comment.id != c.id
});
and here :
//----------v--------------------v
this.$set(this.post, 'comments', this.post.comments) ;
Update :
i was assuming that you a property called post in your data object as follows:
data(){
return{
post:[]
...
}
}
so in this case you should remove any this before post variable.
Alright, I realized that the culprit was an extra this in this.post.comments.filter((comment).
The working code is this:
delComment(c, post) {
const payload = {
token: this.token,
cid: c.id
}
axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
.then( (res)=> {
post.comments = post.comments.filter((comment)=>{
return comment.id != c.id
});
this.$set(post, 'comments', post.comments) ;
})
.catch( error => {
console.log(error);
});
},
Thanks guys for sharing your thoughts!

Categories

Resources