I have the following function:
export function request(
searchKey,
apiEndpoint,
path,
params,
{ additionalHeaders } = {}
) {
const method = "POST";
return _request(method, searchKey, apiEndpoint, path, params, {
additionalHeaders
}).then(response => {
return response
.json()
.then(json => {
var my_json = update(params)
const result = { response: response, json: json };
return result;
})
});
}
I want to export the variable my_json to another .js file. I already tried with export { my_json }, but it only works if I do that on the top of the document, which doesn't work in my case. Does anyone have an idea?
You can't export a variable which is inside a function but you can definitely get the value stored in my_json by the help of a callback function written in another javascript file.
Try using:
export function request(
searchKey,
apiEndpoint,
path,
params,
{ additionalHeaders } = {},
callback
) {
const method = "POST";
return _request(method, searchKey, apiEndpoint, path, params, {
additionalHeaders
}).then(response => {
return response
.json()
.then(json => {
var my_json = update(params);
callback(my_json);
const result = { response: response, json: json };
return result;
})
});
}
and in the other file define a function callback like:
function callback(data){
// assign this data to another variable so that one can use it
console.log(data)
}
and while calling the request function add one more argument as callback.
Hope this helps.
Related
I'm trying to upload file to a server.
const uploadFileCall = (file) => {
const formData = new FileReader();
formData.readAsArrayBuffer(file);
return axios({
method: 'post',
url: `file/${file.name}`,
data: {
fileContent: formData.result,
},
});
};
How to wait with a call api till formData will be ready? Should I use callback or create a new promise to wait for a prepared file?
You can handle it with the FileReader API using the onload() method
Look at this link the documentation is pretty clear. You should be able to adapt your code with this example.
You have to make call back from your axios call to action.
//post Call
function postCall(url, data, callbackProgressUpload = null) {
Date.prototype.toJSON = function () {
return moment(this).format();
}
const requestOptions = {
method: 'POST',
headers: authHeader(),
body: JSON.stringify(data),
onUploadProgress: function (progressEvent) {
// var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
if (callbackProgressUpload)
callbackProgressUpload(progressEvent);
}
};
return axios.post(baseUrl + url, data, requestOptions).then(
response => {
return response;
}
).catch(function (error) {
return Promise.reject(error);
});
}
*************************************
//service Call
function storeFiles(imagesData, orderId, folder, callback) {
return SC.postCall(`${url}`, fileData, (response) => {
callback(response);
}
);
}
********************************
//action
export function storeFiles(imagesData, orderId, folder) {
return dispatch => {
return orderService.storeFiles(imagesData, orderId, folder, (progress) => {
var percentCompleted = Math.round((progress.loaded * 100) / progress.total);
console.log('percentCompleted', percentCompleted)
}).then(
response => {
return response;
},
error => {
return Promise.reject(error);
}
)
}
}
I am writing a simple js function to return an array of strings fetched using the fetch API. Whenever I try to run code, I get this error: TypeError: callback is not a function
This is my code
function getFlavors(franchise, callback) {
const fetch = require('node-fetch');
let flavors= [];
fetch('url', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ "franchise": franchise })
})
.then(res => res.json())
.then(json => {
json.forEach(element => {
flavors.push(element.flavor)
});
// console.log(flavors);
callback(flavors); <-- VALUES DISPLAYED ON CONSOLE
})
.catch(error => {
console.log(error);
})
}
let benJerrysFlavors = [];
getFlavors("ben&jerrys",benJerrysFlavors);
I am able to see the values on the console but when attempting to return the array from function, I get the callback error
Any ideas as to what might be the issue?
It should be called with a callback function passing the data to it. And you can uptate your array then with the returned data:
let benJerrysFlavors = [];
getFlavors("ben&jerrys", (ret) => {
benJerrysFlavors = ret;
});
Try to change from:
callback(flavors)
To:
callback.push(...flavors)
Suppose I create a BookController and have a function like the example below in this controller:
import Fetch from './Fetch.js';
// GET
async function getAllBooks() {
const books = await Fetch.get('/books');
}
Still in the BookController.js file, could I export this function to call it in another js file as below?
function getAll() {
return getAllBooks();
}
export default {
getAll,
};
Another thing, is it possible to transform the const books into a global variable and export that variable so that I can use it anywhere?
Fetch.js
// Fetch.js
const _apiHost = 'https://api.example';
async function request(url, params, method = 'GET') {
const options = {
method,
headers: {
'Content-Type': 'application/json'
}
};
if (params) {
if (method === 'GET') {
url += '?' + objectToQueryString(params);
} else {
options.body = JSON.stringify(params);
}
}
const response = await fetch(_apiHost + url, options);
if (response.status !== 200) {
return generateErrorResponse('The server responded with an unexpected status.');
}
const result = await response.json();
return result;
}
function objectToQueryString(obj) {
return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
}
function generateErrorResponse(message) {
return {
status : 'error',
message
};
}
function get(url, params) {
return request(url, params);
}
function create(url, params) {
return request(url, params, 'POST');
}
function update(url, params) {
return request(url, params, 'PUT');
}
function remove(url, params) {
return request(url, params, 'DELETE');
}
export default {
get,
create,
update,
remove
};
In javascript we can use global variable with the use of window object.
declare book variable like window.books="some value" intead of const books.
in the same way use function also:
window.getAll = () => {
return getAllBooks();
}
and get value anywhere.
I'm making a GET request with Axios in a React-Redux project, and I get the following error:
TypeError: "config.method.toLowerCase is not a function"
request Axios.js:43
wrap bind.js:11
apiCall api.js:32
apiCall api.js:29
... ...
api.js is a file from my own project. bind.js and Axios.js is from the Axios library. This is my api function:
export function apiCall(method, path, data){
let url = backendDomain + path
let config = {
method: [method],
url: [url],
data : [data],
headers:{
"Content-Type":"application/json",
"Accept":"application/json"
}
}
return new Promise((resolve, reject)=>{
return axios(config).then(res=> {
return resolve(res.data)
}).catch(err => {
return reject(err.response);
})
})
The function that makes use of apiCall() is this function:
export function authUser(url, userData, method){
return (dispatch) => {
return new Promise((resolve, reject)=>{
return apiCall(method, "/"+`${url}`, userData)
.then((data) => {
...
resolve();
})
.catch(err=>{
...
reject();
})
})
}
}
Do you think there's something wrong with my code or is there something wrong with the library? When I use authUser to dispatch my action (for Redux State), I double checked that "method" is a String, I console.logged typeof method in api.js, and it returned string.
Edit:
I tried calling toString() to the method parameter passed into apiCall(), but it didn't work:
let reMethod = method.toString();
const config = {
method: [reMethod],
url: [url],
data : [data],
headers:{
"Content-Type":"application/json",
"Accept":"application/json"
}
}
As mentioned in my comment, you're providing an array when axios expects a string:
const config = {
method: reMethod,
url: url,
data : data,
headers:{
"Content-Type":"application/json",
"Accept":"application/json"
}
}
In my project, I use this modified axios function to make an API request:
// api.js
function request (method, path, { query, params }, fields) {
query = escapeQuery(query); // make query string
return axios[method](`${API.URL}${path}?${query}`, {
...fields,
params
});
}
let methods = {};
['post', 'get', 'patch', 'delete', 'put'].forEach(method => {
methods[method] = (...args) => request(method, ...args);
});
So in actual case, like this:
import API from 'api.js';
...
getSomePages (state) {
var config = {
headers: { 'x-access-token': state.token }
};
let query = { 'page': state.selected_page };
return new Promise((resolve, reject) => {
API.get(`/myapipath`, {query}, config).then(...);
});
},
...
When I call API.get() like the above, it works very well. The problem is when I call API.post. It seems that it cannot distinguish the correct field. For example, when I call:
likePost (state, post_id, user_id) {
var config = {
headers: {
'x-access-token': state.token,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var data = {
post_id, user_id
};
return new Promise((resolve, reject) => {
API.post(`/myapipath`, {data}, config).then(...);
});
},
This API.post call keeps failing, so I looked up the request and found that it doesn't have headers - all the fields I've sent are in the request body.
So I tried something like:
API.post(`/myapipath`, {}, config, data)...
API.post(`/myapipath`, data, config)...
API.post(`/myapipath`, {data, config})...
etc...
but it all failed. It looks like they all cannot understand which is the header. How can I solve this?