Pass Fetch Request to another Fetch Request in React Native - react-native

I'm fairly new to react native so be gentle please. I have a double fetch request inside componentDidMount which works as expected:
componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
}).then((response) => response.json())
.then((responseText) => {
if (responseText.status.status === 'success'){
fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + responseText.payload.access_token,
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
})
}else{
alert('Something has gone wrong.');
}
})
}
I have to use the get token fetch request everytime i need to make a fetch request throughout my app. I was wondering if there is a way to set up the get token fetch request (maybe in a different file) so i can call/import it when i need, then pass a second fetch to it somehow rather than having to write all my fetch requests as above.
Hopefully what i'm asking makes sense - i can provide more code if needed.
Thanks in advance

Try is with await:
React Component
async componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
const tokenRequest = await getToken();
if (tokenRequest.status.status === 'success'){
const response2 = await fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + tokenRequest.payload.access_token,
'Content-Type': 'application/json',
},
})
const responseData = await response2.json();
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
}else{
alert('Something has gone wrong.');
}
}
Somefile.js
export const getToken = async () => {
const response = await fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
})
const responseText = await response.json();
return responseText
}
Don't forget to import 'Somefile.js' to the react component.

Related

seting auth token in react native not working

i am trying to set auth token in react native but it is not working.the api call to the url is woeking and data is saved to db but the token doesnot work
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(function (response) {
console.log('working');
ReactSession.setStoreType('Bearer', response.data.token);
ReactSession.set('username', 'Meon');
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
i get this error
console.log(response); returns the following
I use AsyncStorage together with fetch to set mine and then when i want to use it , I also call AsyncStorage from '#react-native-async-storage/async-storage';
After setting the state like this,
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
I try to simulate a Login
To login looks like this :
FunctionLogin = async () => {
let item = {email, password};
fetch('http://192.168.1.101/api/auth/sign-in', {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) => {
if (responseJson.message === 'OK') {
var token = responseJson.token;
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('token', token);
navigation.replace('Dashboard');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}
To use it in any page, I use it like this , later i reference the function in useEffect
showdata = async () => {
let token = await AsyncStorage.getItem('token');
alert(token);
};
Suppose I want to get transaction list from my endpoint to display data I do it like this
getTransactionsList = async () => {
let token = await AsyncStorage.getItem('token');
let email = await AsyncStorage.getItem('email');
var url = 'https://192.168.1.101/api/user-data/get-transactionby-email/';
fetch(url + email, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
};
Then suppose i want to call it inside useEffect, I do like this
useEffect(() => {
getTransactionsList();
});
Thats what and how i do it and it works fine. If you also know how to use Redux, its still a good one as well.

How do I use Async Storage to save Data Locally after calling fetch in react native?

I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

React native parsing data

Hi everyone i'm newbie in react native and i'm stuck to pass my data to my second page in via my api i get only one message my token for the first log and undefined and i don't understand why
if you could explain me why my day will be better thanks :)
const SignIn = () => {
const navigation = useNavigation();
const [userEmail, setUserEmail] = useState();
const [userPassword, setUserPassword] = useState();
const [isLoading, setLoading] = useState(true);
const onCheck = async () => {
// console.log(userPassword, userEmail);
try {
const response = await fetch(
'API',
{
method: 'POST',
headers: new Headers({
'Content-Type': `application/json`,
}),
body: JSON.stringify({email: userEmail, password: userPassword}),
},
);
const json = await response.json();
const token = json.data.access_token;
const getMe = await fetch(
`API`,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': `application/json`,
},
},
);
const jsonMe = await getMe.json(token);
const data = jsonMe.data;
await AsyncStorage.setItem('token', token);
console.log(token);
console.log(jsonMe.data);
navigation.push('HrProfile', token);
} catch (error) {
console.log(error);
}
};```
so i hope it's could help some dev
In this form you must pass your token inside headers i tried with authorization up the headers but it stupid
oh and never use in asynchronous function await + .then because await already wait a response so it's useless to call wait + wait
enjoy ;)
const navigation = useNavigation();
const [userEmail, setUserEmail] = useState();
const [userPassword, setUserPassword] = useState();
const [isLoading, setLoading] = useState(true);
const onCheck = async () => {
// console.log(userPassword, userEmail);
try {
const response = await fetch(
'Your api[for example /login] ',
{
method: 'POST',
headers: new Headers({
'Content-Type': `application/json`,
}),
body: JSON.stringify({email: userEmail, password: userPassword}),
},
);
const json = await response.json();
const token = json.data.access_token;
const getMe = await fetch(YourApi forother example /getMe or other
``,
{
method: 'GET',
'Content-Type': 'application/x-www-form-urlencoded',
headers: {
Authorization: `Bearer ${token}`,
Accept: `application/json`,
'Content-Type': `application/json`,
},
},
);
const jsonMe = await getMe.json();
const data = jsonMe.data;
//Faire la requette ici pour le get me qui va me donner
// je récupère le token pour pouvoir l'envoyer dans le local storage
await AsyncStorage.setItem('token', token);
console.log(token);
console.log(jsonMe);
console.log(data);
navigation.push('HrProfile', token);
} catch (error) {
console.log(error);
}
};

Axios React upload jpg

I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.
My code here
const axiosMultipart = axios.create({
timeout: 3000,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data'
}
})
uploadDocs(token,type,photo){
let data = new FormData();
data.append('photo', photo);
data.append('type', type);
return axiosMultipart
.post(
`uploadDocs`,
{data},
{
headers: {
Authorization: token,
},
}
)
.then((response) => {
return response.data;
})
.catch((error) => console.log("uploadDocs: " + error));
};
Server response is error_code 400
What is wrong here?
Also I have code on php with a working request
Try With Below Code,
var photo = {
uri: file,
type: 'image/jpeg',
name: 'photo.jpg',
};
var FormData = require('form-data');
var form = new FormData();
form.append('photo', photo);
form.append('filetype', filetype);
axios({
method: 'post',
headers: {
"Accept": "application/json",
'Content-Type': 'multipart/form-data',
"Authorization": authData
},
data: form,
url: `${base_url}`,
}).then(async (result) => {
console.log("uploadFile detail Response===>", result);
}).catch((error) => {
console.log("uploadFile detail error===>", error);
callback({ status: false, result: error })
});

415 coming back from requesting a token Spotify API

I'm trying to receive a token from Spotify api. Unfortunately I keep on receiving 415. Could you help me and let me know what am I doing wrong?
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
form: {
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.SPOTIFY_ID + ':' + process.env.SPOTIFY_SECRET).toString('base64')),
'Content-Type': 'application/json'
}
}).then(token => {
return token;
}).catch(e=> {
console.log(e);
return e.response;
});
};
module.exports = {
getToken
};
415 error code is related to problem with wrong content type or content encoding, (https://httpstatuses.com/415)
I do not know axios but please take a look on the example on spotify github https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L74
According to this issue on github (https://github.com/spotify/web-api/issues/321), try to use content-type 'Content-Type': 'application/x-www-form-urlencoded'
There is example withs axios
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "client_credentials"
},
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: "YOUR-CLIENT-ID",
password: "YOUR-CLIENT-SECRET"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
});
It works!!!
What I've done was:
- change Content-Type for 'application/x-www-form-urlencoded'
- client_id and client_secret were taken from header and posted before grant_type in body
- changed 'data' to 'params'
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
params: {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(token => {
return token;
}).catch(e=> {
return e.response.data;
});
};
And it resulted with a beautiful looking token \m/
After spending one hour trying to figure out how to get the token, I came up with this answer! :)
const axios = require('axios');
const express = require('express');
const app = express();
const client_id= 'YOURCLIENTID';
const client_secret = 'YOURCLIENTSECRET';
app.get('/api/token', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
grant_type: 'client_credentials'
},
json: true,
})
.then(body => {
res.send(body.data.access_token);
})
.catch(e => {
console.log(e.response.data);
});
});
app.listen(3000, () => {
console.log('Server Listening on port 3000');
});
If you making API call from client side (browser), try this solution:
getTokken() {
const urlSpotify = "https://accounts.spotify.com/api/token";
axios({
method: "post",
url: urlSpotify,
data: "grant_type=client_credentials",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.REACT_APP_SPTID_KEY, // User ID
password: process.env.REACT_APP_SPCS_KEY, // User Secret
},
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}