How do I use Async Storage to save Data Locally after calling fetch in react native? - 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);
});

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.

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

How to get Html code by fetching web API response?

When we are trying to fetch html code via fetch API response but we are enable to get it because it return "Unexpected Token <"
onLoginService2 = async () => {
try {
var hittingURl = "https://members.iracing.com/membersite/Login?username=dave#rms55.com.au&password=rms55Pa55&utcoffset=-600&todaysdate=1558055491688&checkbox=0";
const myRequest = new Request(hittingURl.toString(),
{
method: 'POST',
headers: {
'Accept': 'text/html',
'Content-Type': 'text/html;charset=ISO-8859-1',
},
timeout: 1000,
// body: JSON.stringify("")
}
);
fetch(myRequest)
.then((response) => console.log("abcdefghijklmon--> "+JSON.stringify(response)))
.then((data) => {
console.log("RESPONSERR----> ",data+"");
// this.setState({ isLoading: false })
// this.onLoginSuccessFull(responseJson)
})
.catch((error) => {
this.setState({ isLoading: false })
console.log("response--31" + error);
})
} catch{
}
// }
}
The response of first then has a method .text(), which return Promise
Try this
fetch(myRequest)
.then(resp => resp.text())
.then(text => {
//text is html
})
*Just copy the above and run in console to see the result.

FacePlusPlus, "error_message": "MISSING_ARGUMENTS: api_key", with React Native fetch request

I'm fairly new to react native and I'm trying to test out using the FacePlusPlus API (https://console.faceplusplus.com/documents/5679127).
Here, I've tried putting 'api_key' in the body, however, I've also tried putting it in headers too. Neither has worked.
componentDidMount() {
var url = 'https://api-us.faceplusplus.com/facepp/v3/detect';
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_key: 'blahblahblah',
api_secret: 'blahblahblah',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
In render(), I put console.log(this.state.data) where data is an array to see the response, however all I keep getting is
Object {
"error_message": "MISSING_ARGUMENTS: api_key",
}
To solve this problem you have to set Content-Type header to 'application/x-www-form-urlencoded'
and pass your arguments as formData.
I put the example with using 'request' npm package.
const request = require('request');
request.post({url:'https://api-us.faceplusplus.com/facepp/v3/compare', formData: {
api_key: 'your api key',
api_secret: 'your api secret',
image_url1: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/George_Lucas_cropped_2009.jpg/220px-George_Lucas_cropped_2009.jpg',
image_url2: 'https://imgix.bustle.com/uploads/getty/2018/6/13/e4c5921d-3e23-4f13-87fe-0180005d0ace-getty-929360234.jpg?w=970&h=582&fit=crop&crop=faces&auto=format&q=70'
}}, (err, httpResponse, body) => {
if (err) {
return console.error('error', err);
}
console.log('success ', JSON.parse(body));
});

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