React Native fetch URL - passing hook value as parameters - react-native

What is the proper way to pass a useState hook value as a query parameter in a REACT NATIVE fetch url? The function returns that my jwt is malformed it's not reading the value of the hook properly. The two hooks are below, I'm trying to use those as query parameters in the fetch URL AND header authorization. $Are typically JQuery, but not sure the proper syntax for React Native - Expo.
const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();
useEffect(() => {
const fetchSubUploads = async (userID, user) => {
const response = await fetch(
`content/subs/uploads/**${userID}**`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer **${user}**`
},
});
let data = await response.json();
console.log(data);
setSubscriptions(data.subscriptionUploads);
return data;
};
const getUser = async() =>{
const loggedInUser = await AsyncStorage.getItem('fariToken');
if(!loggedInUser){
Alert.alert('Please Login')
}if(loggedInUser){
setUser(JSON.stringify(loggedInUser))
}
}
fetchSubUploads();
}, []);

I suggest spitting the useEffect in two. One effect is obviously dealing with making the fetch request with the appropriate data, user and userID, and so should have a dependency on these values, while the other effect deals with loading some "initial" state values from storage.
Example:
const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();
useEffect(() => {
const getUser = async () => {
const loggedInUser = await AsyncStorage.getItem('fariToken');
if (loggedInUser) {
setUser(JSON.stringify(loggedInUser));
} else {
Alert.alert('Please Login');
}
}
getUser();
}, []);
useEffect(() => {
const fetchSubUploads = async (userID, user) => {
const response = await fetch(
`content/subs/uploads/**${userID}**`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer **${user}**`
},
}
);
const data = await response.json();
console.log(data);
setSubscriptions(data.subscriptionUploads);
return data;
};
if (user && userID) {
fetchSubUploads(userID, user);
}
}, [user, userID]);

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.

Axios interceptors not adding headers on some requests in React Native, iOS only

I have an Axios instance:
const axiosInstance = axios.create({
baseURL: API_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
axiosInstance.interceptors.request.use(async (config: any) => {
const accessToken = await getSecureValue('accessToken');
config.headers.Authorization = `Bearer ${accessToken}`;
return config;
});
And some API functions:
export const getProfile = async () => {
const response = await axiosInstance.get('/user/profile');
return response.data;
};
export const postContact = async (message: string) => {
await axiosInstance.post('/contact', { message });
};
A user can log in and it calls getProfile(), that all works.
But when I try the postContact:
const handleSendPress = async () => {
try {
await postContact(textInput);
} catch (error) {
console.log(error);
}
};
It comes back with an error from the server that the Authorization header is missing.
Adding a console.log() in the interceptor I can see that it is running before the request.
I'm running Android and iOS in emulators, and this only happens on iOS.
I'm very lost what this could be, since getProfile() works but postContact() doesn't and they both use the same Axios instance.

why passing params do not refresh and have to refresh the new page update

i am trying to pass params to next page by calling id from previous
page. but when you enter the next page the data does not appear
immediately and you have to refresh the page which takes quite a long
time, and faithfully calling new data, what appears is the previous
data, you have to refresh the page to bring up new data. what is the
solution?
first page code
...//
onPress={() => {
setId(item.ID);
navigation.navigate('Rekap_Bencana', {
params: id
});
}}
...//
const [dataBencana, setDataBencana] = useState();
const [id, setId] = useState();
useEffect(() => {
getData();
}, []);
const getData = () => {
fetch('http://192.168.0.103/aplikasi/restapi.php?op=getDatabencana')
.then(response => response.json())
.then(json => {
// console.log(json);
setDataBencana(json);
// console.log(dataBencana);
});
};
params page code
const Rekap_Bencana = () => {
const route = useRoute();
const navigation = useNavigation();
const {params} = route.params;
useEffect(() => {
getData();
console.log(params);
}, []);
const [data, setData] = useState();
const getData = () => {
fetch('http://192.168.0.103/aplikasi/restapi.php?op=getBencanaDetail', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: params,
}),
})
.then(res => res.json())
.then(resp => {
setData(resp);
console.log(resp);
});
};

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);
}
};

How to use Async Storage Axios

Problem:
I have create react-native application.And there I am using AsyncStorage with axios in like this to handle my API calls.This is how that looks like.
import axios from "axios";
import { AsyncStorage } from "react-native";
// TODO: Replace this with actual JWT token from Keycloak
axios.defaults.headers.post["Content-Type"] = "application/json";
// Create axios instance for api calls
var instance = null;
export const setAuth = async () => {
const user = await AsyncStorage.getItem("jwt");
AsyncStorage.getItem("jwt").then(token => {
instance = axios.create({
baseURL: "",
timeout: 150000,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json"
}
});
instance.interceptors.response.use(
function(response) {
return response;
},
async function(error) {
if (error.response.status) {
return error;
}
}
);
});
};
export const Get = (route, data) => {
instance || setAuth();
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
);
};
export const Post = (route, data) => {
instance || setAuth();
return instance.post(route, JSON.stringify(data));
};
export const Put = (route, data) => {
debugger;
instance || setAuth();
return instance.put(route, JSON.stringify(data));
};
export const AddAdmin = (route, data) => {};
Becuase of the asynchronus property of AsyncStorage it is not creating the axios instanceinstance = axios.create({.The problem is with after this line .So can someone help me with this.I do not have any idea to find out what is wrong with this. Thank you.
You can give a try to this.
export const setAuth = async () => {
const token = await AsyncStorage.getItem('jwt');
instance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
// remaining Code
};
export const Get = (route, data) => {
function getData(){
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
)
}
if(instance) return getData()
return setAuth().then(getData)
}