how to store a auth token in react native from api responce - react-native

i am trying to store the response.data.token into sessionstorage or localstorage how can i do it from inside the axios then
const getdata = async () => {
var date2 = moment(mydate2).format('DD/MM/YYYY');
var date = moment(mydate).format('DD/MM/YYYY');
var todaydate = moment(new Date()).format('DD/MM/YYYY');
if (date == todaydate && date2 != todaydate) {
var Data56 = {
name: name,
email: email,
babyname: babyname,
phone: nuber,
period: date2,
// baby_date: date,
};
} else {
var Data56 = {
name: name,
email: email,
babyname: babyname,
phone: nuber,
// period: date2,
baby_date: date,
};
}
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data56,
})
.then(async response => {
await AsyncStorage.setItem('token', `${response.data.token}`);
alert('sucess ');
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
};
i am trying to store the response.data.token into sessionstorage or localstorage how can i do it from inside the axios then

==> Update Your code like this:-
.then(function async(response) {
try{
await AsyncStorage.setItem('token', response.data.token);
}catch{
console.log("Catch Function")
}

Setting data to Asyncstorage works asynchronous so you need set with await like this:
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(async (response) => {
await AsyncStorage.setItem('token', `${response.data.token}`);
alert("sucess ");
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}

Related

how to make the photo field optional in react native

in React native can anyone tell me how to make the responsePath optional thats how i make it optional using && but it is not working in case of photo field can anyone help me out below are the codes.first is of redux how i send the data using formdata and 2nd is of component where i called this api function of redux.
redux//
export const addMember = (formValues, actions, key, resourcePath) => {
return async dispatch => {
const token = await AsyncStorage.getItem('userToken');
const formdata = new FormData();
formdata.append('name', formValues.name);
formdata.append('age', formValues.age);
formdata.append('relation', formValues.relation);
formdata.append('gender', key);
formValues.mobile && formdata.append('mobile', formValues.mobile);
formValues.blood_group &&
formdata.append('blood_group', formValues.blood_group);
formValues.height && formdata.append('height', formValues.height);
formValues.weight && formdata.append('weight', formValues.weight);
formValues.email && formdata.append('email', formValues.email);
resourcePath && formdata.append('photo', resourcePath);
console.log(formdata, 'for mdata');
let response = await fetch(
'https://theeasylab.com/admin/api/auth/add-family-member',
{
method: 'post',
body: formdata,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
},
)
.then(res => {
return res;
})
.catch(error => {
actions.setErrors(error?.response?.data.error);
return error.response;
});
dispatch({
type: 'ADD_MEMBER',
payload: response,
});
};
};
component //
submitAddMemeber = (values, actions) => {
this.props
.addMember(
values,
actions,
this.state.itemValue.key,
this.state.resourcePath
)
};

React native cli formdata is sending data in a object it should not be in any object and array

im trying to post data using formdata but formdata sending data in a object..it should not be in any object or array,,in Reactjs web its working fine it just send like this lab_id : 1 ..how can i solve this issue ..please let me know what can i do,,,
//data is sending like this
{"_parts" : [[
['date', current_date],
['test_ids[]', tests_data],
['lab_partner_id', lab_id],
['booking_for', selectedMember],
['time', time_slot],
['health_package_id', health_packages_details],
['payment_mode', payment_mode],
]]},
// it should be like this only
health_package_id: health_packages_details
//my code
const onPay = async (
current_date,
tests_data,
lab_id,
selectedMember,
time_slot,
health_packages_details,
payment_mode,
) => {
const token = await AsyncStorage.getItem('userToken');
dispatch(startSubmitting());
const url = `/auth/make-booking`;
let formdata = new FormData();
formdata.append('lab_partner_id', lab_id);
formdata.append('booking_for', selectedMember);
formdata.append('date', current_date);
formdata.append('time', time_slot);
health_packages_details &&
formdata.append('health_package_id', health_packages_details);
tests_data && formdata.append('test_ids[]', tests_data);
formdata.append("payment_mode", payment_mode);
const response = await api
.post(
url, formdata ,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log("res hhh", res);
if (res.data.payment_mode == "ONLINE") {
initiatePaymentInterface(res.data);
}
dispatch({
type: 'BOOKING',
payload: response,
});
setLoading(false);
initiatePaymentInterface(res.data);
return res;
})
.catch(error => {
actions.setErrors(error.response.data.error);
failedPaymentInitiate(error.response);
setLoading(false);
});
dispatch(stopSubmitting());
};

How to use Spotify 30sec previews with Expo React native app

I have been trying to use the Spotify API in my expo app but every tutorial or wrapper I find doesn't seem to work.
I would specifically like to access the 30-second song previews and track/song searching features.
If anyone could provide some guidance or point me towards a working demo of any kind that would be awesome.
Thanks!
Found parts of the solution in https://docs.expo.dev/guides/authentication/#spotify
const discovery = {
authorizationEndpoint: 'https://accounts.spotify.com/authorize',
tokenEndpoint: 'https://accounts.spotify.com/api/token',
};
var client_id = ''; // Your client id
var client_secret = ''; // Your secret
export default function spotifyLogin(props) {
const [request, response, promptAsync] = useAuthRequest(
{
clientId: '',
scopes: ['user-read-email', 'user-read-playback-state', 'playlist-modify-public','playlist-modify-private','playlist-modify-public','playlist-read-private','user-read-recently-played'],
// In order to follow the "Authorization Code Flow" to fetch token after authorizationEndpoint
// this must be set to false
usePKCE: false,
redirectUri: makeRedirectUri({
//scheme: 'your.app'
}),
},
discovery
);
React.useEffect(() => {
if (response?.type === 'success') {
const { code } = response.params;
//save code to local storage
props.saveLogin(code)
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();
}}
/>
);
}
export const getFirstTokenData = async (code) => {
var dataToSend = {
code: code,
redirect_uri: makeRedirectUri(),
grant_type: 'authorization_code'};
//making data to send on server
var formBody = [];
for (var key in dataToSend) {
var encodedKey = encodeURIComponent(key);
var encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
//POST request
var response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST', //Request Type
body: formBody, //post body
headers: {
//Header Defination
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')),
},
})
try{
return await response.json()
}catch (error){
console.log(error)
}
}
export const getRefreshTokenData = async (refreshToken) => {
console.log(refreshToken)
console.log(refreshToken + " going in for refresh")
var dataToSend = {
refresh_token : refreshToken,
grant_type: 'refresh_token'};
//making data to send on server
var formBody = [];
for (var key in dataToSend) {
var encodedKey = encodeURIComponent(key);
var encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
//POST request
var response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST', //Request Type
body: formBody, //post body
headers: {
//Header Defination
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')),
},
})
try{
return await response.json()
}catch (error){
console.log(error)
}
}
The above takes care of auth and getting refresh tokens, below takes care of searching for a track. To get 30 second previews there is a preview property in the return data for getTrack()
const apiPrefix = 'https://api.spotify.com/v1';
export default async ({
offset,
limit,
q,
token,
}) => {
const uri = `${apiPrefix}/search?type=track&limit=${limit}&offset=${offset}&q=${encodeURIComponent(q)}`;
console.log('search begin, uri =', uri, 'token =', token);
const res = await fetch(uri, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
}
});
const json = await res.json();
//console.log('search got json', json);
if (!res.ok) {
return [];
}
return json
// const {
// tracks: {
// items,
// }
// } = json;
// // const items = json.tracks.items;
// return items.map(item => ({
// id: item.id,
// title: item.name,
// imageUri: item.album.images
// ? item.album.images[0].url
// : undefined
// }));
console.log('search end');
};
export const getTrack = async(trackID, token) => {
const uri = `${apiPrefix}/tracks/${trackID}?market=ES`;
const res = await fetch(uri, {
method: 'GET',
headers: {
// Accept: `application/json`,
// Content-Type: `application/json`,
Authorization: `Bearer ${token}`,
}
});
const json = await res.json();
//console.log('search got json', json);
if (!res.ok) {
return [];
}
return json
}
Once upon a time, I worked on a similar application as a test. It's a bit outdated, but I believe Spotify has not changed its API much in the meantime.
Hope this caa help
https://github.com/kubanac95/spotify-test

How to passing result of http request inside async in ExpressJS?

I have below code
async send(user, data) {
const postData = {
'data': 'john',
'secret': 'secret'
};
const dataJson = JSON.stringify(postData);
const options = {
hostname: 'example.com',
path: '/send',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': dataJson.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(dataJson);
req.end();
//---------------
let postResult = // HERE I WANT TO GET WHAT HTTP POST REQUESTED (e.g dataJson.body?)
//---------------
let result;
try {
result = await this.users.collection('users').updateOne(
{
_id: user
},
{
$set: {
// I WANT TO USE THAT HERE
data1 : postResult,
data2 : data2
}
},
{ maxTimeMS: consts.DB_MAX_TIME_USERS }
);
} catch (err) {
log.error('DB', 'UPDATEFAIL id=%s error=%s', user, err.message);
err.message = 'Database Error, failed to update user';
err.code = 'InternalDatabaseError';
throw err;
}
return { success: true };
}
How to get those data to outside variable?
I almost crazy about this, been searching on google and not found anything
I am using express and native-http to make http request, are there any native-curl maybe?
thank you very much for all the help
Your current code is using callback to retrieve result, so you can initiate data variable to outside callback function
let data = '';
const req = https.request(options, (res) => {
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
})
And also there are other easier way to make http request with nodejs. you can check axios that support Promise and async/await.
you can use syntax like this with axios
const response = await axios.get('/user?ID=12345');
way more easier.

How should i use asyncstorage.setItem in this fetch method?

i want to add the async storage method to save my json response,
but i don't know how to add there specifically
i have already tried like this
UserRegisterationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch('http://192.168.1.7/test/user_registration.php', {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
AsyncStorage.setItem('token', responseJson)
// this._onValueChange(STORAGE_KEY, responseData.id_token),
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
i am getting my alert successfully but i don't know how should i add the responseJson or if i have used it correctly or not
You can use the asynchronous system or save successfully without using it.
To run asynchronously:
.then(async (responseJson) => {
await AsyncStorage.setItem('token', responseJson.id_token);
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
If your responseJson data is this:
Object {
id_token : "myid"
}
Use the getItem function on the following screen to check the value.
async componentDidmount() {
const tokens = await AsyncStorage.getItem('token');
alert(tokens); // You can see 'myid'
}
The JSON response is an object and you can't store the object directly in AsyncStorage. You can only store the object by converting it into a string.
To store the object:
AsyncStorage.setItem('KEY', JSON.stringify(object))
To retrieve the object:
const jsonObjectString = AsyncStorage.getItem('KEY')
const jsonObject = JSON.parse(jsonObjectString)