Returning different Promise data with axios - promise

I am trying to work with the Marvel api and using multiple sources of data with an axios.get method. I am at the moment returning with the characters ID to display the characters info and the comics associated with them. I made a function to get the comics using another axios.get which I am trying to assign to a variable so I can pass that to my template engine. I consoled the variable and got [object Promise], when I pass to my engine nothing appears. I am unsure what I am doing wrong and using then() and catch() is kinda confusing me even when I read the documentation.
function getCharactersComic(character){
var charactersComics;
return axios.get('https://gateway.marvel.com:443/v1/public/characters/' + character[0].id + '/comics?limit=10', {
params:{
ts: timeStamp,
apikey: marvelKey.pubKey,
hash: marvelHash
}
})
.then(response =>{
charactersComics = response.data.data.results;
console.log("comics" + charactersComics);
return charactersComics;
})
.catch(err => {
console.log('This is the error from comics: ', err.response);
})
router.get("/:id", function(req,res){
axios.get('https://gateway.marvel.com:443/v1/public/characters/' + req.params.id,{
params: {
ts: timeStamp,
apikey: marvelKey.pubKey,
hash: marvelHash
}
})
.then(response =>{
let character = response.data.data.results;
let comics = getCharactersComic(character);
console.log('inside call ' + comics);
res.render('character', {character: character , comics:comics});
})
.catch(error => console.log('This is the error from id: ', error));
});

Related

how to upload image in register API in strapi?

In defaut registration API, I need to uplaod the image of user in registration API. So how could I manage it ? I'm sending in a formData and it works fine. I can see (binary) in network.
I tried to add image field and it works in admin panel but from API side I tried to send the file in key names like files, profileImage.
I didn't get the error in res. I got success in res.
Issue: When I reload the admin panel, I didn't get user's profile image.
Try this way. I used in react and it works fine for me.
signUpHandler = () => {
console.log("SignUp data ::: ", this.state);
let data = {
username: this.state.signUpForm.username.value,
phone: this.state.signUpForm.phone.value,
email: this.state.signUpForm.email.value,
password: this.state.signUpForm.password.value
}
axios.post('http://0.0.0.0:1337/auth/local/register', data)
.then(res => {
console.log(res);
return res.data.user.id;
})
.then(refId =>{
const data = new FormData();
data.append('files', this.state.selectedFile);
data.append('refId', refId);
data.append('ref', 'user');
data.append('source', 'users-permissions');
data.append('field', 'profileImage');
return axios.post('http://0.0.0.0:1337/upload', data)
})
.then(res =>{
console.log(res);
alert("You registered successfully...");
this.props.history.push('/login');
})
.catch(error =>{
console.log(error);
})
}
First, you will have to customize your user-permission
To do so, you will have to understand this concept: https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html
Then you will have to find the function you want to update - in your case, the register function.
And tada here it is https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L383.
So you will have to create ./extensions/users-permissions/controllers/Auth.js with the same content as the original file.
Then you will have to add
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
const uploadFiles = require('strapi/lib/core-api/utils/upload-files');
on the top of your file.
And in your function use this
const { data, files } = parseMultipartData(ctx); to parse data and files.
Then you will have to replace ctx.request.body by data to make sure to use the correct data.
After that you will have to add this after the user creation line
https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L510
if (files) {
// automatically uploads the files based on the entry and the model
await uploadFiles(user, files, { model: strapi.plugins['users-permissions'].models.user })
}
Solution for Strapi v4:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer XXXX");
var formdata = new FormData();
formdata.append("files", fileInput.files[0], "XXX.png");
formdata.append("refId", "46");
formdata.append("field", "image");
formdata.append("ref", "plugin::users-permissions.user");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://localhost:1337/api/upload", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Can the completion of one async call be sequenced before the start of another using useEffect?

I'm trying to use useEffect in my React app but also refactor things more modularly. Shown below is the heart of actual working code. It resides in a Context Provider file and does the following:
1. Calls AWS Amplify to get the latest Auth Access Token.
2. Uses this token, in the form of an Authorization header, when an Axios GET call is made to an API Endpoint.
This works fine but I thought it would make more sense to move Step #1 into its own useEffect construct above. Furthermore, in doing so, I could then also store the header object as its own Context property, which the GET call could then reference.
Unfortunately, I can now see from console log statements that when the GET call starts, the Auth Access Token has not yet been retrieved. So the refactoring attempt fails.
useEffect(() => {
const fetchData = async () => {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert('Error getting authorization token: '.concat(error))
})
}};
await axios.get('http://127.0.0.1:5000/some_path', config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert('Error getting data from endpoint: '.concat(error));
});
};
fetchData();
}, [myContextObject.some_data]);
Is there a way of refactoring my code into two useEffect instances such that the first one will complete before the second one starts?
You could hold the config object in a state. This way you can separate both fetch calls and trigger the second one once the first one finished:
const MyComponent = props => {
const myContextObject = useContext(myContext);
const [config, setConfig] = useState(null);
useEffect(() => {
const fetchData = async () => {
const config = {
headers: {
Authorization: await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert("Error getting authorization token: ".concat(error));
})
}
};
setConfig(config);
};
fetchData();
}, [myContextObject.some_data]);
useEffect(() => {
if (!config) {
return;
}
const fetchData = async () => {
await axios
.get("http://127.0.0.1:5000/some_path", config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert("Error getting data from endpoint: ".concat(error));
});
};
fetchData();
// This should work for the first call (not tested) as it goes from null to object.
// If you need subsequent changes then youll have to track some property
// of the object or similar
}, [config]);
return null;
};

Test for react async action creator - undefined data

I have the following action and test case - when I run this test(jest) - I am seeing TypeError: Cannot read property 'data' of undefined in action creator, not sure what is missing here? I am providing mockData that is expected. is it because there is an async nested here? but i am using `.then but it still fails.
Action creator:
export const getUser = ({
uname,
apiendpoint,
}) => {
const arguments = {};
return async (dispatch) => {
await axiosHelper({ ---> this will return axios.get
arguments,
path: `${apiendpoint}/${uname}`,
dispatch,
}).then(async ({ data, headers }) => { -- getting error at this line.
dispatch({ type: GET_USER, payload: data });
dispatch({ type: GET_NUMBEROFUSERS, payload: headers });
});
};
};
Test:
describe('Get User Action', () => {
let store;
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
beforeEach(() => {
store = mockStore({
data: [],
});
});
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
})
const arguments = {
uname: 'user123',
apiendpoint: 'test',
};
const url = 'https://www.localhost.com/blah/blah';
it('should get a User', () => {
fetchMock
.getOnce(url, {
data: mockData, -->external mock js file with user data {}
headers: {
'content-type': 'application/json'
}
});
const expectedActions = [
{
type: 'GET_USER',
data: mockData
},
{ type: 'GET_NUMBEROFUSERS' }
];
return store.dispatch(actions.getUser(arguments)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
You are using await AND then on the same function (axiosHelper for example).
This is wrong usage and will lead to many errors of undefined.
You either use a callback-function or a .then() or an await but not 2 or all of them.
I recommend to watch some tutorials/explanations about async/await because it's really important to understand what a Promise is.
What's happening in your cas is that axiosHelper is executed 2 times, because if it's finished the then-part will fire up but at the exactly same time (because it's async) the await finishes and code-execution continues the parent flow. This brings up race-conditions and, as i said, will lead to undefined because you are executing the same logic twice or more.

Vue.js 2 & Axios - Filtering an api for a search feature

I'm trying to filter through a collection of films that i'm retrieving using axios. This is so i can compare it to a search string for a search feature. Everything works fine except when using the computed property it returns Cannot read property 'filter' of undefined" but when i check the vue dev tool it says that the computed property contains the array of films which doesn't really add up. The code is as follows.
created(){
this.fetchFilms();
},
methods:{
fetchFilms(page_url){
let vm = this;
// storing the page url
page_url = page_url || '/api/films'
axios.get(page_url)
.then(response => response)
.then(response => {
this.films = response.data;
vm.makePagination(response.meta, response.links);
})
.catch(err => console.log(err));
},
makePagination(meta,links){
let pagination = {
current_page: this.films.meta.current_page,
last_page: this.films.meta.last_page,
next_page_url: this.films.links.next,
prev_page_url: this.films.links.prev
}
this.pagination = pagination;
}
},
computed: {
filteredFilms () {
return this.films.data.filter((film) => {
return film.film_name.toLowerCase().match(this.searchString.toLowerCase())
})
},
}
This is how the data is returned
films:Object
data:Array[10]
links:Object
meta:Object
Any help is appreciated.
You're probably accessing filteredFilms before the request is done. I don't see any code to wait for the request. You could make filteredFilms check if the data is there and return an empty list if it isn't.

Making concurrent call in Bluebird promise using Sequelize findOne method . Returns undefined

I want to verify existence of specific user data from multiple tables to make it a concurrent call i am using Bluebird Promise.Prop like given below. Data is acceded Using sequelize ORM.
Promise.props({
user: (()=>{
return User.findOne({
where: {username: req.user.username}
});
}),
comments: (()=>{
return comments.findOne({
where: {username: req.user.username}
});
})
}).then((result)=> {
console.log(result.user.name, result.comments.count);
});
I also tried with a nested promise but doesn't succeeded. like
Promise.props({
user: (()=>{
return User.findOne({
where: {username: req.user.username}
}).then((user)=>{
console.log(user.name); // even here i am getting undefined
});
}),
comments: (()=>{
return comments.findOne({
where: {username: req.user.username}
});
})
}).then((result)=> {
console.log(result.user.name, result.comments.count);
});
You are not clear if result.user is undefined, or result.user.name is undefined.
I expect the latter.
You pass an object with 2 keys to Promise.props.
But both of the keys are a function, and not a promise. So promise.props sees the function, not the promise.
The result should still have the 2 functions.
Try
Promise.props({
user: User.findOne({
where: {username: req.user.username}
}),
comments: comments.findOne({
where: {username: req.user.username}
})
}).then((result)=> {
console.log(result.user.name, result.comments.count);
});
Other good ways are Promise.all, or if you know how many promises you have then use Promise.join
Promise.join(
User.findOne({
where: {username: req.user.username}
}),
comments.findOne({
where: {username: req.user.username}
}),
(user, comment) => {
console.log(user.name, comments.count);
}
);
You are returning the Promise itself rather than the resolve value. The results need to be collected in the promise resolution and an then be passed along.
// collect values in this object
const values = {};
// run all promises
Promise.all([
model.findOne()
.then((val) => {
// assign result 1
values.val1 = val;
return Promise.resolve();
}),
model.findOne()
.then((val) => {
// assign result 2
values.val2 = val;
return Promise.resolve();
}),
])
.then(() => {
// the values will be collected here.
console.log(values);
});

Resources