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);
}
};
Related
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.
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.
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]);
I am using ra-postgraphile as dataprovider for react-admin project and i need to intercept the error api response. Is there any error object or function available for that? if yes, Can I get a documentation.
Also posted an issue in ra-postgraphile repo.
Source Code
const httpLink = createHttpLink({
uri: Config.postgraphileUrl
});
const authLink = setContext((_, { headers }) => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
'Content-Type': 'application/json'
}
}));
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
useEffect(() => {
(async () => {
const dataProvider = await pgDataProvider(client);
setDataProvider(() => dataProvider);
})();
}, []);
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.