seting auth token in react native not working - react-native

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.

Related

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

I am unable to get API data in redux store

I am trying to build an app to add and delete items. I am using an API(Link of API documentation below). I can post and get data from API to the store. But I am unable to show the saved items on UI. And the getBooks function seems to be not working. Can anyone please help me?
Link to API documentation: https://www.notion.so/Bookstore-API-51ea269061f849118c65c0a53e88a739
Here is the code, I have used.
export const addBook = (book) => async (dispatch) => {
await fetch(url, {
method: 'POST',
body: JSON.stringify(book),
headers:{
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(() => dispatch({type: ADD_BOOK, book}))
}
export const removeBook = (index) => async (dispatch) => {
await fetch(`${url}/${index}`, {
method: 'DELETE',
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(() => dispatch({ type: REMOVE_BOOK, index }));
};
export const getBooks = () => async (dispatch) => {
await fetch(url)
.then((res) => res.json())
.then((book) => {
const booksArray = [];
Object.keys(book).forEach((key) => {
booksArray.push({
item_id: key,
author: book[key][0].author,
title: book[key][0].title,
category: book[key][0].category,
});
});
dispatch({ type: GET_BOOKS, booksArray});
});
};

React Native fetch URL - passing hook value as parameters

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

Pass Fetch Request to another Fetch Request in 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.

fetch response.json() gives responseData = undefined

When using fetch:
fetch(REQUEST_URL, {
method: 'get',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) =>
{
response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
console.log(responseData);
});
}).catch(function(err) {
console.log(err);
})
.done();
The following works works, do you know why? :
JSON.parse(response._bodyText)
The chaining response should look more like this, specifically the response.json part. Then you should get an Object back in console.log.
.then(response => response.json())
.then(response => {
console.log(response)
}
Fetch is a little hard to get your head around. I am new to this so dont shoot me down if flames here but response data is another promise and you need to return response data and then handle that promise with yet another then statement where you can finally log the response, also your are missing some return statements in your promises:
var makeRequest = function(){
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
return response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
addTestToPage(responseData.title);
return responseData;
})
.catch(function(err) {
console.log(err);
})
}
function addTestToPage(textToAdd){
var para = document.createElement("p");
var node = document.createTextNode(textToAdd);
para.appendChild(node);
var element = document.getElementsByTagName("body")[0];
element.appendChild(para);
}
makeRequest();
hope that helps see: https://jsfiddle.net/byz17L4L/
Here's how it finally worked out in my case:
fetch('http://localhost:3001/questions', {
method: 'GET',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(response => { return response.json();})
.then(responseData => {console.log(responseData); return responseData;})
.then(data => {this.setState({"questions" : data});})
.catch(err => {
console.log("fetch error" + err);
});
}
because you didn't return response.json() in the first then.
import React, {useEffect} from 'react';
useEffect(() => {
getRecipes();
}, []);
const getRecipes = async () => {
const response = await fetch(
`https://........`
);
const data = await response.json();
console.log(data);
Use this method You can easily fatch data.
fetch(weatherIng + zipCode +apiKey)
.then(response => response.json())
.then(response => {
console.log(response.main);
this.setState({
weather: ((response.main.temp * (9/5))-459.67).toFixed(0),
humidity:((response.main.humidity * (9/5))-459.67).toFixed(0)
})
It will think that you are trying to declare something if you don't enclose it in its own:
.then(response => {
console.log(response.main);
}) . " around the this.setState