Reputation: 623
I built a backend in Express to fetch Instagram feed images then send the images URL to my front end built with ReactJs. If I use instagram-node to fetch the images URL then send it to front end then it everything works, but if I do it manually with axios, it would not work.
This is my code with instagram-node npm packet:
ig.user_media_recent('user_id', function(err, medias, pagination, remaining, limit) {
if(err) console.log(err);
else{
var inst = [];
medias.map(function(content){ inst.push(content.images.thumbnail.url)});
res.send(inst);
}
});
If I do the above then the backend will get the URL and then send it to my front end, but if I do like below with axios
axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=token')
.then(function(res){
console.log(res.data.data[0].images.standard_resolution.url);
res.send(res.data.data[0].images.standard_resolution.url);
}).catch(function (err){
res.send(err.body);
})
then it would not send anything. The console.log still print out the correct URL but the res.send would not do anything. It would not even show the URL when I go to my backend localhost. Any idea why?
Upvotes: 0
Views: 457
Reputation: 21124
It seems res.send(res.data.data[0].images.standard_resolution.url)
is having some issue here. This is how normally we do such things in react. After the completion of the promise you need to fire an action with the response payload, then a reducer will return the new state. Finally the UI will get re-rendered with updated data. That's how react works.
axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=token')
.then(function(res){
console.log(res.data.data[0].images.standard_resolution.url);
return {
type: GET_INSTA_FEEDS,
payload: response.data
}
}).catch(function (err){
res.send(err.body);
})
Then write a reducer
to get this data and return a new state properly.
// ------------------------------------
// Reducer
// ------------------------------------
export const initialState = {
instaFeeds: []
}
[GET_INSTA_FEEDS]: (state, action) => {
return { ...state, instaFeeds: action.payload }
}
Bind that state to your component via connect HOC. That's it
Upvotes: 2