I meet something strange and found no answer.
I met the warning as below:
Possible Unhandled Promise Rejection(id:0)
TypeError: undefined is not a function (evaluating '_api2.default.getResp(URL, "GET")'....
Below is shortened code like what my source code is.
The "Pass Code" works fine and "Warning Code" shows warning as above.
Why Api.getResp goes wrong but Api.loggedin.getResp works OK? They are so similar!!
Warning Code
const GetData = {
async fetchFeed() {
console.log(`Api = ${Api}`); // Api = [Object Object]
console.log(`Api.getResp = ${Api.getResp}`); // Api.getRest = undefined
const { success, content } = await Api.getResp(`${URL}`, 'GET');
if (success) {
.....
}
},
};
module.exports = FetchApi;
Pass Code
const GetData2 = {
async syncData(): void {
const { success, content } = await Api.loggedin.getResp(`${URL}`, 'GET');
.....
}
}
API
const Api = {
async getResp(url: string, method: string): Object {
try {
const response = await fetch(url,
{ method,
null,
{ 'content-type' : 'application/json' },
});
......
} catch (error) {
console.log(`fetch url: ${url}, error: ${error}`);
}
return result;
},
loggedin: {
async getResp(url: string, method: string): Object {
const accessToken = await this._getAccessToken();
....
return result;
},
},
Related
So I'm trying to send an image to our server with react native using GraphQL query and I don't know why but it always return an error : [CombinedError: [Network] Network request failed].
The query :
import { graphql } from '../../gql';
import { gql, useMutation } from 'urql';
const AddProfilePicture_Mutation = graphql(`
mutation AddPicture_Mutation ($userId: ID!, $picture: Upload!) {
uploadProfilePicture(input: {
userId: $userId
picture: $picture
}) {
id
}
}`);
export const useAddProfilePicture = () => {
const [{fetching, error}, execute] = useMutation(AddProfilePicture_Mutation);
return {
error: !!error,
fetching,
addProfilePicture: execute,
}
}
and the code :
const pictureHandler = async () => {
const options = {
mediaType: 'photo' as MediaType,
includeBase64: true,
selectionLimit: 1,
};
const profilePicture = await launchImageLibrary(options);
if (profilePicture.assets?.[0].fileSize && profilePicture.assets?.[0].fileSize > MAXFILESIZE) {
showError(t('profileScreen.PictureSize'));
}
if (profilePicture.assets?.[0].uri && profilePicture.assets[0].fileName && profilePicture.assets[0].type) {
// const myBlob = await fetch(profilePicture.assets[0].uri).then(r => r.blob());
const blob = new Blob([profilePicture.assets[0].base64 as BlobPart], {
type: profilePicture.assets[0].type,
});
const file = new File([blob], profilePicture.assets[0].fileName, { type: `${profilePicture.assets[0].type}`});
const {error} = await addProfilePicture(
{ userId: userId!, picture: file},
{ fetchOptions: { headers: { 'graphql-require-preflight': '' } } }
);
if (!error) {
showSuccess(t('profileScreen.PictureSuccessAdded'));
navigation.navigate('UserProfile');
} else {
console.log(error);
showError(t('profileScreen.PictureErrorAdded'));
}
};
};
I've been trying everything I found on the web, Formdata, react-native-blob-util and rn-fetch-blob. If I try sending anything else then a File, the server reject it and says for exemple:
Variable 'picture' has an invalid value: Expected type org.springframework.web.multipart.MultipartFile but was java.util.LinkedHashMap]
Update :
After long research and help from other programmers. We never did found the answer. We open a new access point in the backend specifically for the uploaded picture and used a regular fetch post.
I am making a simple web app using async javascript
I am using api from the open weather map, everything works well except the updating ui
and I keep getting this error TypeError: Cannot read properties of undefined (reading 'temp') at updateUI (app.js:66)"
i think the problem is passing the data to the project data object beacause when i turned it to an array everything worked
this is my server side code
note : i required express, cors and boyparser
let entry = [];
projectData["entry"] = entry;
//post request
app.post('/add', function(request, response) {
let data = request.body;
console.log(data);
let latestEntry = {
temp: data.temp,
date: data.date,
content: data.content
}
entry.push(latestEntry);
response.send(projectData);
});
this is my client side code that I wrote, the updating ui function is not working properly and i am not getting an outout of the temperature however the result shows in the console
//
//Post function
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log("error", error);
}
}
//update UI function
const updateUI = async () => {
const request = await fetch('/all');
try {
const allData = await request.json();
document.getElementById('temp').innerHTML = `Current temperature: ${allData[0].temp} degree celsius`;
document.getElementById('date').innerHTML = `Today's date: ${allData[0].date} `;
document.getElementById('content').innerHTML = `I feel: ${allData[0].content}`;
} catch (error) {
console.log("error", error);
}
}
I have been working on js-ipfs (0.49.0) and this was working fine but I started getting some issues, anyway I have finally come back to look at the code again and the connection works fine but when I attempt to upload I get a new error
Object is not async iterable
I am not sure what that means or how to address in my code a lot of the examples are for react and not vue
Any pointers much appiciated.
methods: {
async getIpfsNodeInfo() {
try {
// Await for ipfs node instance.
node = await ipfs
// console.log(node)
// Call ipfs `id` method.
// Returns the identity of the Peer.
const { agentVersion, id } = await node.id()
this.agentVersion = agentVersion
this.id = id
// Set successful status text.
this.status = 'Connected to IPFS 😊'
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
onFileSelected(event) {
this.selectedFile = event.target.files[0]
this.saveIPFS()
},
async saveIPFS() {
try {
for await (const result of node.add(this.selectedFile)) {
this.fileContents = result
this.getIPFS()
}
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
ipfs.add returns a single object since ipfs#0.48.0 - you need to change:
async saveIPFS() {
try {
for await (const result of node.add(this.selectedFile)) {
this.fileContents = result
this.getIPFS()
}
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
to:
async saveIPFS() {
try {
this.fileContents = await node.add(this.selectedFile)
this.getIPFS()
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
See the blog post for more: https://blog.ipfs.io/2020-07-20-js-ipfs-0-48/#ipfs-add
Here is my code
handleLogin = async()=> {
const { navigation } = this.props;
const errors = [];
Keyboard.dismiss();
this.setState({ loading: true });
if(this.state.email!=''){
if(this.state.password!=''){
fetch('http://192.168.1.10:8000/api/login',{
method:'post',
headers:{
'Content-Type':'application/json',
'Accept': 'application/json'
},
body:JSON.stringify({
"email":this.state.email,
"password":this.state.password
})
})
.then((response)=> response.json())
.then((res)=>{
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
if(this.state.store==='{"error":"Unauthorised"}'){
Alert.alert("Error", "These credentials do not match our records");
}
else {
Alert.alert("Success","You have succesfuly login",
[
{
text: 'Continue', onPress: () => {
Actions.NavigationCalling();
}
}
],
{ cancelable: false })
}
}).catch((error)=>{
console.error(error);
});
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert Password")
}
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert email")
}
var store=JSON.stringify(res)
Im storing data in store variable that print output like this
{"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YjYzNTY4NjNkNmYxNzBhYjdlYjVmNWRiN2MxNWU1NTUzNDc3OWUyZjM5Mjc5NWU4ODMzMjM3NDU1Y2Q3ODg1YzYzZTc0NDg2MmNjYzk2In0.eyJhdWQiOiIxIiwianRpIjoiOThiNjM1Njg2M2Q2ZjE3MGFiN2ViNWY1ZGI3YzE1ZTU1NTM0Nzc5ZTJmMzkyNzk1ZTg4MzMyMzc0NTVjZDc4ODVjNjNlNzQ0ODYyY2NjOTYiLCJpYXQiOjE1ODA5MzA2MzYsIm5iZiI6MTU4MDkzMDYzNiwiZXhwIjoxNjEyNTUzMDM2LCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.A1NZcxICOu8mudwrIrozG5FYiQxWyz1O8LcHFcaOvgXUlTkgUIuGuwxif74goMwCLkWrm3wIwZSKwMAxCAk35Ao9VZEsV3uOlelWtsjJY7u-o00baCUl3dZWJeBHLLfSODM719Oinrfepp5VGaGZ4r--rMqMnNljVEoUP8GuM0l_7rY-SA7dhXkj4a8TwogkZOzf1_0ZvgNYmM30Z_CU0umM72Iqcys-URnzb80HONI4_cVcYExqmU94UqhNsNJ9aMIDXR4WdMGzDBzhRat_E75u7Rbt67UKUbbwALv3J1qhGRb-kkE_DGR3DyAxlcNvMy21CR4b4obDE4e96GYb-7R7fLw0PiVtiyFTgLeL2Ldvw4YV8_v2TwF5zLgkh0VCqfjUTIbAir9ytjDBPDzXFy7G4mAR6qJYNPSHtgwzBcMuS2B4FWZruWg-0QbHiBFFQrDGISaf5jUTSCmiSbpd3eTKAhiifBE6eGNnzErlsG1WAn8L7zK233l1b7qDSoahIrK4PTllgsdEzFtI4sXpy_9mEbRmGmEjOTXZcUyvkFm6aajXrRwWGrhSMFIeFqRd2BNTnrh2Igwl9x7Dcj89VgXKGXyh-hP4ESwT5yHAynNhVfhaXAu1kdnkzhwzk5cDlKlYawvX02g83THN6UAElj2bttIutM-fZ1ViLIOA98k"}}
But i want to store just token in new state and pass to other screen
how can i get only token from json object and store into newstate and pass into new screen
Thanks in advance I'm new in the React native
You can access the token by doing res.success.token or you can map the json response to an object.
.then((res)=>{
var token = res.success.token // did you try doing this?
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
....
And to pass the token to another screen you can use the screen props or use redux, however, i would set it in a static variable to be accessed globally by all the screens.
I am working on a react native app that does pretty much the same that you are trying to do, i created a class called ApiService that has the following function:
static async post(url: string, payload?: object, headers?: HeadersInit_): Promise<ApiResponse> {
return await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
}).then(r => r.json().then(o => {
var mapper = new ApiResponse();
mapper.success = o.success;
mapper.result = o.success ? JSON.stringify(o.result) : o.error;
return mapper;
})).then(response => {
if (response.success)
return response;
throw ApiError(response);
});
}
The ApiResponse class looks like this:
class ApiResponse {
public success: boolean;
public result: string;
}
To access the auth token globally, i am setting the token in a static variable in a class that can be accessed everywhere.
class AbstractService {
private static sessionToken: string;
public static setSessionToken(value: string): void {
AbstractService.sessionToken = value;
}
public static getSessionToken(value: string): string {
return AbstractService.sessionToken;
}
If you want to store the token to be reused, you can use react-native-secure-key-store
I have a problem that I do not know how to solve...
I have an api token saved in AsyncStorage, and when I want do fetch to rest I need this api token, but I do not know how to do it.
I have file Functions.js with AsyncStorage functions.
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
getApiToken: function(){
try {
return Functions.retrieveItem('api_token');
} catch (error) {
console.warn(error.message);
}
},
File with fetch functions. (Api.js)
I tested with an asynchronous function, but not found...
async get(url) {
try {
var api = await Functions.getApiToken();
if (!api)
api = "";
let opt = {
method: 'get',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
};
return fetch(baseUrl + url + api, opt);
} catch (error){
console.warn(error);
}
},
When I did the fetch function, it worked for me without problems
And the screen file Home.js
componentDidMount() {
Api.get('home').then( response => {
this.setState({
profiles: response.profiles,
});
});
}
Please modify your Functions.js code a bit -
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
async getApiToken{
try {
let token = await retrieveItem('api_token');
return token;
} catch (error) {
console.warn(error.message);
}
}
Hope this helps you!