Need to extract name value from json array of the output - javascript

I am unable to extract the name variable from the graph output of the following react code. trying to store the name value from the json output received from the api in my state variable in React. How do i do it?
state = {
auth: false,
username: '',
access_token: '',
app_name: [],
};
responseFacebook = response => {
{/*console.log(response);*/}
if(response.status !== 'unknown')
this.setState({
auth: true,
username: response.name,
access_token: response.accessToken
});
graph.setAccessToken(this.state.access_token);
graph.get("/me/accounts", function(err, res) {
let response = res;
console.log(response.data[0]);
});
console.log(this.state);
}

Maybe because your checking the second console.log outside the callback. In javascript the callbacks( the function inside the get call ) are trigerred later, when the API completes, hence you will not get anything in the console.log outside the callback, if you rewrite your example it might work.
state = {
auth: false,
username: '',
access_token: '',
app_name: [],
};
responseFacebook = response => {
if(response.status !== 'unknown') {
this.setState({
auth: true,
username: response.name,
access_token: response.accessToken
});
graph.setAccessToken(this.state.access_token);
graph.get("/me/accounts", (err, res) => {
let response = res;
this.setState({username:response.data[0]});
console.log(this.state);
});
}
}
Event loop reference

Related

Put Not Working to Update with Axios Mongoose

I am trying to set up an edit feature to edit a post. Right now I am trying to update a specific post by ID and then I'll make it dynamic.
I can get axios to send the PUT request but I don't receive any indication that it is received on the router. Also the ID I have set it showing up correctly in the URL.
I'm not sure how to send the data over to the router so it can find the ID.
Edit component
function handleSubmit(event){
event.preventDefault()
axios ( {
url: `/api/${props.data[0]._id}`,
method: 'PUT',
headers: { "Content-Type": "multipart/form-data" },
id: props.data[0]._id
})
.then(() => {
console.log(`data has been sent to the server from axios: ${props.data[0]._id}`)
})
.catch(() => {
console.log('Data could not be sent from axios')
})
}
Router
router.put('/:id', async (req, res) => {
try {
const updatedGratitude = await PostGratitude.findByIdAndUpdate(req.params.id)
res.status(200).json(updatedGratitude)
} catch (err){
next(err)
}
})
if you are editing a post then you should send the data in the request as well
like a title: "" and description: "" or something and in the in the router, you could write something like this :
function handleSubmit(event) {
event.preventDefault()
axios({
url: `/api/${props.data[0]._id}`,
method: 'PUT',
headers: { "Content-Type": "application/json" },
data: {
title: '',
description: ''
}
})
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
})
}
you need to pass the arguments as to what to update as well, here is an example of a code that I wrote
router.put('/updatentry/:id',fetchuser, async (req, res) => {
var success = false
try {
const { title, description } = req.body
let newentry = { title: title , description: description
}
let old_entry = await Journal.findById(req.params.id);
if (!old_entry) {
return res.status(404).send({ success, error: 'Not Found'})
}
const update_entry = await Journal.findByIdAndUpdate(req.params.id, { $set: newentry }, { new: true })
return res.send(res: update_entry)
} catch (error) {
return res.status(500).send(error: 'Internal Server Error')
}
})
This is because you forgot the update body on method. Try this:
PostGratitude.findByIdAndUpdate(req.params.id, req.body)
instead of :
await PostGratitude.findByIdAndUpdate(req.params.id)
Because mongoose can not know what to update :D

Can't redirect after login?

Getting a TypeError: Cannot read property '$router' of undefined when trying to redirect after login. I have tried various methods on the router instance but it is undefined according to the console?
Login action (inside store):
login({ commit, dispatch }, { username, password }) {
const querystring = require('querystring');
this.$axios.$post('connect/token', querystring.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
username,
password,
grant_type: 'password'
}))
.then(function (response) {
dispatch('setToken', {
token: response.access_token,
expiresIn: response.expires_in
});
this.$router.push({name: 'home' }); // this line is the issue
})
.catch(errors => {
console.dir(errors);
});
},
You just need to preserve this before calling it again inside .then(...) like:
login({ commit, dispatch }, { username, password }) {
// Store `this` inside variable vm here
const vm = this;
const querystring = require('querystring');
vm.$axios.$post('connect/token', querystring.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
username,
password,
grant_type: 'password'
}))
.then(function (response) {
dispatch('setToken', {
token: response.access_token,
expiresIn: response.expires_in
});
// Use this for debugging purpose only
console.log( vm.$router )
// You can now access `$router` safely here now
vm.$router.push({name: 'home' });
})
.catch(errors => console.dir(errors));
},
Your problem is that you use this inside an regular function, that means that this is binded to the function and not the vue instance, change it to an arrow function:
.then((response) => {
dispatch('setToken', {
token: response.access_token,
expiresIn: response.expires_in
});
this.$router.push({name: 'home' }); // this line is the issue
})
Other solution is to .bind() it:
.then(function (response) {
dispatch('setToken', {
token: response.access_token,
expiresIn: response.expires_in
});
this.$router.push({name: 'home' }); // this line is the issue
}.bind(this))

Axios - Cant set and get data in object

I am using the Axios library for my ajax requests so I created an instance of axios.
When I hit the endpoint /user/login, the success response will return me a token that I will use in the header for future calls as the API is secured.
The problem is when I do a console.log(authUser) the object is empty even though in the .then(), I am setting authUser.bearerToken.
Why is this happening? And what's the solution? Thanks. See code below.
var ax = axios.create({
baseURL: 'http://api.site.test',
timeout: 5000,
headers: {
'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx'
}
});
var authUser = {};
// log the user in
ax.post('/user/login', {
email: 'e#maiiiiiiiiil.com',
password: 'ThisIsACoolPassword123!'
})
.then(function (response) {
// set the bearer token
authUser.bearerToken = response.data.token;
ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
})
.catch(function (error) {
console.log(error);
});
console.log(authUser);
It's because its async. The code that talks to /user/login takes some time but your code continues.
So the order is
Create base axios
Define authUser as empty object
Send a request to /user/login
Console.log authUser
Get the response from the post request
You can see it more clearly if you put 3 console logs.
var ax = axios.create({
baseURL: 'http://api.site.test',
timeout: 5000,
headers: {
'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx'
}
});
var authUser = {};
console.log('authUser is ' + authUser);
// log the user in
ax.post('/user/login', {
email: 'e#maiiiiiiiiil.com',
password: 'ThisIsACoolPassword123!'
})
.then(function (response) {
// set the bearer token
authUser.bearerToken = response.data.token;
ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
console.log('2. authUser is ' + authUser);
})
.catch(function (error) {
console.log(error);
});
console.log('3. authUser is ' + authUser);
You will see it in the following order: 1, 3, 2 and not 1, 2, 3.
ax.post is asynchronous ( non blocking ) so it won't execute in the order you want it to execute i.e it can execute any time ( or concurrently ). you either have to use callbacks or async...await to handle this
function f() {
var ax = axios.create({
baseURL: 'http://api.site.test',
timeout: 5000,
headers: {
'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx'
}
});
var authUser = {};
var response;
; ( async () => {
// log the user in
try {
response = await ax.post('/user/login', {
email: 'e#maiiiiiiiiil.com',
password: 'ThisIsACoolPassword123!'
})
} catch(ex) {
response = ex;
} finally {
if ( Error[Symbol.hasInstance](response) )
return console.log(response);
authUser.bearerToken = response.data.token;
ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
}
})();
console.log(authUser)
}

Javascript: How can I Choose a specific Part from an Output

easy question:
FunctionOutput: Promise {
_c:
[ { promise: [Object],
resolve: [Function],
reject: [Function],
ok: [Function],
fail: [Function],
domain: null } ],
_a: undefined,
_s: 1,
_d: true,
_v:
{ body:
{ token_type: 'bearer',
access_token: 'token',
expires_in: 7776000,
refresh_token: 'token' },
statusCode: 200 },
_h: 0,
_n: true }
This is my Output from a function and I want to specify output "access_token" How do I do that?
console.log("token is"+ data._v.body.access_token);
does not work...
Pls help Thanks a lot!
What you've shown is a promise. You'd use the promise via its then method:
data
.then(function(result) {
// Use result here
})
.catch(function(err) {
// Handle error here
});
We can't tell you how to access access_token on the result, because we don't know what part of what you've shown (if any) will be the resolution value. It may be result.access_token, or result.body.access_token. But you won't be able to access it except in a then callback.
data
.then(function(result) {
console.log(result.body.access_token);
})
.catch(function(err) {
// Handle error here
});
You can use destructuring if you just want to have the access_token
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
// whatever you're calling that returns that object
const mockRequest = () => new Promise(resolve => resolve(res))
// response
const res = {
body: {
token_type: 'bearer',
access_token: 'token',
expires_in: 7776000,
refresh_token: 'token'
},
statusCode: 200
}
/*
calls async function it then waits until its
finsihed the request and "then" calls the then with the data
Normally we would just return what ever comes back
i.e (data) => data.body.access_token
But we can use a new ES6 feature which just returns the object
name passed instead
i.e ({body}) => { token_type: 'bearer' ...
*/
function getAccess() {
mockRequest()
.then(({body: {access_token}}) => console.log(access_token))
.catch(err => console.log(err))
}
getAccess();
/*
// Or using es7 features such as async await
async function getAccessES7() {
const {body:{access_token}} = await mockRequest();
return access_token;
}
getAccessES7();
*/

Getting values from response

I am getting the response from an external api like the given below screenshot.
How can i get the value of id i.e., 3991938
Here is how i do the request.
$http.post('http://api.quickblox.com/users.json', {
token: quickbloxapitoken,
user: {
email: email,
login: email,
password: password
}
}, {
'Content-Type': 'application/x-www-form-urlencoded'
})
.then(function(results) {
console.log('1');
console.log(results);
console.log('2');
})
.catch(function(response) {
console.log('Error', response.status, response.data.errors);
});
I tried to do console.log(results.id); and console.log(results.data.id) but i am getting only undefined as the result.
How can i get it.
Your JSON is:
{
data: {
user: {
id: 65
}
}
}
You can acces to user data with results.data.user, eg: results.data.user.id
you id is in user object,
so what you need is :-
results.data.user.id

Categories