Access the `access_token` property in localstorage - javascript

I have saved the token in localstorage: localStorage.setItem ('token', JSON.stringify (res.data)). I am trying to access the access_token property.
JSON.parse(localStorage.getItem(token['access_token']))
It gets error: token is undefined;
getToken = () => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const url = '/oauth2/token';
axios({
method: 'post',
url,
data,
config
})
.then(res => {
if (res.status === 200) {
localStorage.setItem('token', JSON.stringify(res.data))
this.setState({
token: res.data
})
} else {
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.error(err);
alert('error');
});
}

You syntax needs to be corrected to as below
JSON.parse(localStorage.getItem('token'))['access_token']

You can use
var tokenData = JSON.parse(localStorage.getItem('token'));
console.log(tokenData.access_token);
Example how to store object in localStorage
var myObj = {
one: {
title: 'first',
id: 1,
customKey : {
first: "first",
second: "second"
}
},
two: {
title: 'second',
id: 2
},
three: {
title: 'this is the third',
id: 3
}
};
localStorage.setItem('storeObj', JSON.stringify(myObj));
var getObject = JSON.parse(localStorage.getItem('storeObj'));

Related

How to make asynchronous api calls in loop and conditional statements in react js?

[
{
description: "question value1",
subjectId: "",
classId: "",
image:"",
answers: [{ description: "option value", isCorrect: false },
{ description: "option value", isCorrect: true }
],
},
{
description: "question value2",
subjectId: "",
classId: "",
answers: [{ description: "option value", isCorrect: false },
{ description: "option value", isCorrect: true }
],
},
]
I have something like this and now i need to make the post call to api for each question so that once the question is created i get the question ID back and then i can use that ID to create options for that question and if it has image upload the image too and have to wait for each of them to finish how can i do that i really m bad asynchronous progamming, there are sperate API's for creating a question creating a option for the question uploading a image for the question
This what i have tried so far but for some reason its wrong idk
async mapCreatedQuestions(questionId) {
let token = getCookie(process.env.token);
let formData = new FormData();
formData.append("QuestionId", questionId);
formData.append("QuizId", this.state.quizId);
await axios
.post(`api to create a association if question already exists`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {})
.catch((err) => {
console.log("Error !!!.. association");
console.log(err);
this.setState({ loading: false });
});
}
async createOptions(question, questionId) {
let token = getCookie(process.env.token);
question.answers.map((option, index) => {
//options uploaded from here
console.log("this options are for the question", option);
if (option.description.length > 0) {
let formData = new FormData();
formData.append("Description", option.description);
formData.append("QuestionId", questionId);
formData.append("IsCorrect", option.isCorrect);
axios
.post(`api to add answers(options)`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {
console.log("option created", response);
})
.catch((err) => {
console.log("Error !!!.. In options");
console.log(err);
this.setState({ loading: false });
});
}
});
}
async questionImageUpload(questionPicture, questionId) {
let token = getCookie(process.env.token);
//upload the picture of the question
let formData = new FormData();
formData.append("ImageTitle", "quizImage" + questionId);
formData.append("QuestionId", questionId);
formData.append("Image", questionPicture);
await axios
.post(`api to upload image`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {
console.log("image uploaded successfully ", response);
})
.catch((err) => {
console.log(" image upload failed err", err);
this.setState({ loading: false });
});
}
async createEachQuestion (question){
let formData = new FormData();
formData.append("Description", question.description);
formData.append("QuestionTypeId", question.questionTypeId);
formData.append("SubjectId", question.subjectId);
await axios
.post(`apitocreatequestion`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {
this.setState({ questionId: response.data.result });
let questionId = response.data.result;
if (question.questionPicture.toString().length > 0) {
this.questionImageUpload(question.questionPicture, questionId);
}
})
.catch((err) => {
console.log("error in question creationn", err);
});
await this.createOptions(question,questionId);
await this.mapCreatedQuestions(questionId);
}
async mapEachQuestion (){
console.log("this question will be mapped not created", question);
let formData = new FormData();
formData.append("QuestionId", question.questionId);
formData.append("QuizId", this.state.quizId);
await axios
.post(`apitoassociatequestionandquiz`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {
console.log("question asssociated", response);
})
.catch((err) => {
console.log("Error !!!.. association");
console.log(err);
this.setState({ loading: false });
});
}
async createQuestion() {
let token = getCookie(process.env.token);
this.state.questionList.map((question, index) => {
if (question.hasOwnProperty("questionId")) {
//map the existing question id to quiz
this.mapEachQuestion (question)
} else {
this.createEachQuestion (question)
}
});
}
async createQuiz(quiz) {
await this.setQuestionList;
await this.sendQuiz;
this.setState({ loading: true });
let formData = new FormData();
console.log("quiz", quiz);
console.log("this.state.questionList", this.state.questionList);
let id = getCookie(process.env.iId);
formData.append("Description", quiz.Description);
formData.append("Title", quiz.Title);
formData.append("TimeinMinute", quiz.TimeInMinute);
let token = getCookie(process.env.token);
await axios
.post(`apitocreatequiz`, formData, {
headers: {
authorization: `${TOKEN_TYPE}${token}`,
},
})
.then((response) => {
console.log("quiz created successfully. Response =>", response);
//setQuizId in state
this.setState({ quizId: response.data.result });
})
.catch((err) => {
console.log("Error !!!.. when creating the quiz");
console.log(err);
this.setState({loading:false});
});
await this.createQuestion;
this.setState({loading: false});
}
API calls are a promise that data will be returned at some point.
Fortunately async processes have become much easier to deal with recently. You can use Promise.all to capture the data once it's been resolved.
Your data is already in an array so it becomes much easier.
In this first example you can use the Fetch API to get the data, and then gather the data.
function mockApi(n) {
return new Promise((res, rej) => {
setTimeout(() => res(n), 2000);
});
}
const input = [1, 2, 3, 4];
function getData(input) {
// Instead of mockApi(el) use `fetch(url)`
const promises = input.map(el => mockApi(el));
Promise.all(promises).then(data => {
console.log(data);
});
}
getData(input);
In this example you can use async/await:
function mockApi(n) {
return new Promise((res, rej) => {
setTimeout(() => res(n), 2000);
});
}
const input = [1, 2, 3, 4];
async function getData(input) {
const data = input.map(el => mockApi(el));
const output = await Promise.all(data);
console.log(output);
}
getData(input);

React Redux Thunk with callback to another function -- TypeError: Cannot read property 'then' of undefined

I am using react+redux.
I have a modal form with data and images and on success I need to close the modal else display error returned from redux. In the dispatch function I have 1 more callback function to store images to S3. I am returning promise from the redux-thunk but I keep getting "TypeError: Cannot read property 'then' of undefined".
Component
handleSubmit = e => {
e.preventDefault();
if(this.isFieldEmpty()){
this.setState({ message: "All fields are mandatory with at least 1 pic" });
return;
} else {
this.setState({ message: "" });
}
const data = {
name: this.state.name,
description : this.state.description,
points : this.state.points,
attributes : this.state.attributes,
images : this.state.images,
created_by: localStorage.getItem('id'),
}
this.props.createItem(data).then(() => {
this.hideModal();
})
}
const mapDispatchToProps = dispatch => {
return {
createItem: data => {
return dispatch(createItem(data))
},
};
};
Action
const saveItemImages = (images,successcb, failurecb) => {
if(images.length > 0){
const formData = new FormData();
for(var x = 0; x<images.length; x++) {
formData.append('image', images[x])
}
const token = localStorage.getItem('token');
fetch(`${backendUrl}/upload/item-images/`, {
method: "POST",
headers: {
'Authorization': `Bearer ${token}`
},
credentials: 'include',
body: formData
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
successcb(resData.imagesUrl);
});
}else{
res.json().then(resData => {
failurecb(resData.message);
})
}
})
.catch(err => {
console.log(err);
});
} else {
successcb([]);
}
}
export const createItem = data => { return (dispatch) => {
saveItemImages(data.images, imagesUrl => {
data.images = imagesUrl;
return fetch(`${backendUrl}/admin/createItem`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.token}`
},
credentials: 'include',
body: JSON.stringify(data)
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_SUCCESS,
payload: resData
})
return true;
});
}else{
console.log("Save failed");
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: resData.message
}
})
})
}
})
.catch(err => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: `Internal Error -- ${err}`
}
})
});
}, failedMessage => {
let payload = {responseMessage: failedMessage}
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: payload
})
});
};
};
Thanks in advance for any help
You should return a Promise to create async flow for the action like this:
export const createItem = data => dispatch => new Promise((resolve, reject) => {
// do something was a success
resolve();
// do something was a fail
reject();
});

Delete user's profile

In my application I can delete a user's profile using an API.
I don't understand why this code doesn't work.
deleteUser() {
let ctrl = true;
if (ctrl) {
let formdata = new FormData();
const identity = {
MyAppName: {
Username: this.props.cf,
}
};
console.log("identity: ", identity)
formdata.append("Identity", JSON.stringify(identity));
fetch(linktomyapi, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(response => response.json())
.then(responseData => {
console.log("responseData - ", responseData)
Alert.alert("Eliminated.")
global.utente = Utente.clearUserLogged()
Actions.homepage();
})
.catch(err => alert("err:" + err));
}
}
from Identity console.log I receive the right username that I passed.
While about the responseData:
responseData -
{Error: {…}}
Error: {Code: "0000", shortMessage: "Generic Error"}
__proto__: Object
I have tried with CocoaRestClient the api and it works
Where is the problem in your Opinion??

How to dynamically pass a parameter in the get in method?

In the network tab, I send the query 'https://api.spotify.com/v1/search?limit=14&market=US&offset=5&q=abba&type=track,artist'
It does not work: how to set the query to be in that order:
https://api.spotify.com/v1/search?q=mmm&type=track%2Cartist&market=US&limit=10&o
'q' should be after search?
getArtists(query) {
const params = {
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query === 'string') {
params.q = query;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};
getArtists('Abba');
I see a auhtorization error when trying your apis.
{
"error": {
"status": 401,
"message": "No token provided"
}
}
You need to provide the authorization token in the header to fix this.
getArtists(query) {
let params = {
q: query,
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query !== 'string') {
delete params.q;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {headers: {
'Authorization': 'Bearer <AUTHORIZATION TOKEN>},
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};
If you don't have it yet, check out the process here : https://developer.spotify.com/documentation/general/guides/authorization-guide/
Try this
getArtists(query) {
let params = {
q: query,
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query !== 'string') {
delete params.q;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};

function based on other callBack function... react-native

when user wants to to POST somthing he must be singed in(without username & pass).
Problem is i'm trying to make when CreatePost() invoked it will call SingUser() and based on SingUser() fetch request it will call CreatePost() again to let user post after he sign in.
this is in createpost component
CreatePost(){
fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)
}).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status =='inactive'){
//SignUser
}else{
//post
}
}).catch((error)=>{ //later
});
}
here is SingUser() in other file
async function SignUser() {
try{
User.vtoken = await AsyncStorage.getItem('vtoken');
var userTemp={
vtoken: User.vtoken,
ntoken : User.ntoken
}
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=> response.json()).
then((responseJson)=>{
if(responseJson.path == 2){
Save(responseJson, userTemp);}
else return;
}).catch((error)=>{
});
}catch(error){}
}
async function Save(result , userTemp){
try{
await AsyncStorage.setItem('vtoken', result.vtoken);
User.vtoken = result.vtoken;
userTemp.vtoken = result.vtoken;
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=>response.json()).
then((responseJson)=>{
return 'done';
}).catch((error)=>{})
}
catch(error){}
}
export {SignUser}
i hope u understand what im trying to do if there is better way to do it thnx:(
You can do something like this:
const errorCodeMap = {
USER_INACTIVE: 10,
}
const statusMap = {
INACTIVE: `inactive`
}
const METHOD = `POST`
const APPLICATION_JSON = `application/json`
const headerDefault = {
Accept: APPLICATION_JSON,
'Content-Type': APPLICATION_JSON,
}
const who = `post`
async function createPost(payload, options) {
try {
const {
url = ``,
fetchOptions = {
method: METHOD,
headers: headerDefault,
},
} = options
const {
post,
} = payload
const response = await fetch(url, {
...fetchOptions,
body: JSON.stringify(post)
})
const {
status,
someUsefulData,
} = await response.json()
if (status === statusMap.INACTIVE) {
return {
data: null,
errors: [{
type: who,
code: errorCodeMap.USER_INACTIVE,
message: `User inactive`
}]
}
} else {
const data = someNormalizeFunction(someUsefulData)
return {
data,
errors: [],
}
}
} catch (err) {
}
}
async function createPostRepeatOnInactive(payload, options) {
try {
const {
repeat = 1,
} = options
let index = repeat
while (index--) {
const { data, errors } = createPost(payload, options)
if (errors.length) {
await signUser()
} else {
return {
data,
errors,
}
}
}
} catch (err) {
}
}
solve it, I did little adjustments
async CreatePost(){
try{
var response = await fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)});
var responseJson = await response.json();
if(responseJson.status =='inactive' && postRepeat == true){
postRepeat == false;
await SignUser();
this.CreatePost();
}
else{
//posted
}
}catch(err){}
}

Categories