react-native fetch undefined on button press - react-native

I have a function when I press a button to get data
however my app is erroring on fetch undefined
async doNext() {
const response = await fetch(`https://facebook.github.io/react-native/movies.json`);
const jsonData = await response.json();
console.log(jsonData);
}
error:
Possible Unhandled Promise Rejection (id: 0)
undefined is not a function evaluating 'fetch'('https://facebook.github.io/react-native/movies.json'))
I also tried to write it like this:
doTest = async () => {
const response = await fetch(`https://facebook.github.io/react-native/movies.json`);
const jsonData = await response.json();
console.log(jsonData);
}
doNext() {
this.doTest();
}
but got the same error
how do I make 'fetch' defined, if I console.log(fetch) I get undefined

found the problem in my code
self = this;
missing let or var, this was in index.android.js this line alone broke everything no warnings appeared for this

Related

Why if i created a mock i am still getting error?

i am doing testing, i made a test in that test i create a mock for a fake function
jest.mock('#/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
that function is running in my component
onMounted(async () => {
const answer = await getAvailables1()
const answer = await getAvailables2()
const answer = await getAvailables3()
but still i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
if i put like this first getAvailables2
onMounted(async () => {
const answer = await getAvailables2()
const answer = await getAvailables1()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function
if i put like this first getAvailables3
onMounted(async () => {
const answer = await getAvailables3()
const answer = await getAvailables2()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function
also i try with mockResolvedValue, does not worked
export const getAvailables = async () => {
let response
let error
try {
response = await getData()
} catch (err) {
error = err
throw err
}
return { response, error }
}
It looks like you want a mock partial:
jest.mock('#/services/myService', () => {
const originalModule = jest.requireActual('#/services/myService');
return {
__esModule: true,
...originalModule,
getAvailables1: () => Promise.resolve({ foo: 'bar' }),
getAvailables2: () => Promise.resolve({ foo: 'baz' }),
getAvailables3: () => Promise.resolve({ foo: 'bad' }),
/* any other method of your service that gets called */
};
});
This will mock the provided functions in the mock while the rest of the service will function as in the original.
getAvailables() is async function that always returns a promise.
So, in order to mock that function you need to return the mock promise with success or rejected value.
Following is the example of mocking that function which returns success promise.
jest.mock('#/services/myService', () => ({
getAvailables: jest.fn().mockResolvedValue(true)
}))

Manipulate base64 file in expo

I need to manipulate this file I get in Base64 (download it or share it):
const generatePDF = async () => {
const companyReponse = await CompanyService.getCompany();
const peopleResponse = await PeopleService.getPerson(sale.customerId);
const company = companyReponse.response.company;
const people = peopleResponse.response;
const quote = false;
const json = await SaleService.generatePDF({
sale,
company,
people,
quote,
});
await ensureFolderExists();
if (json && json.success) {
const path = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;
await FileSystem.writeAsStringAsync(path, json.data, {
encoding: FileSystem.EncodingType.Base64,
});
const url = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;
Linking.openURL(url);
}
};
using the base64 string returns and searching like this in the browser data:application/pdf;base64,${json.data} I can even see it. but I've tried it in several ways and none of them worked, I believe this one may be closer to success.
[Unhandled promise rejection: Error: Could not open URL 'file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf': file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf exposed beyond app through Intent.getData()]
I solved this issue in this another ask
[https://stackoverflow.com/questions/69738812/problem-to-generate-pdf-from-a-blob-in-an-expo-app-using-filesystem][1]

Parse JSON to model in React Native getting undefined

I'm trying to map my JSON Object to a model class like that:
export class Product {
constructor(props) {
this.name = props.Name
this.items = props.Items
this.price = props.Price
this.productID = props.ProductID
this.medias = props.Medias
}
}
But when I get JSON and try to parse to my Model I'm getting the following error
TypeError: undefined is not an object (evaluating 'mostSoldProductsApiResponse.map'
There's my parse code:
const mostSoldProductsApiResponse = await mostSoldProductsApiCall.json().Products;
const arrayProducts = mostSoldProductsApiResponse.map(function(item) {
return new Product(item.Product)
})
If I don't parse the JSON Object to new Product() constructor, the code works fine. But I would like to organize the code. Therefore I would like to implement Product class.
It might be you are using await not on what you expect.
The line await mostSoldProductsApiCall.json().Products is actually first returning a promise, then awaiting on the resulting promise field Products which is undefined because it is not the result of the promise.
something equivalent to:
const promise = mostSoldProductsApiCall.json() // this is the promise
const unresolvedProducts = promise.Products // this is undefined
const mostSoldProductsApiResponse = await unresolvedProducts // this resolves to undefined
Solution
Use parenthesis to await on the actual promise, like so:
const mostSoldProductsApiResponse = (await mostSoldProductsApiCall.json()).Products
Another option:
const mostSoldProductsApiResponse = await mostSoldProductsApiCall.json()
const arrayProducts = mostSoldProductsApiResponse.Products.map(function(item) {
return new Product(item.Product)
})
Hope this helps!

React Native - useEffect / setState - fetching data from api

I'm learning RN and writing a simple app about lottery results.
I am facing this problem:
I need to print the results that i am fetching from an api when the component mounts, using useEffect and setState. Everything works regarding the api call and the item construction, i can console.log the resulting array [loadedResults] which i want to be 'results' in the state.
But, the state its not being modified so the state object remains always empty.
I am clearly missing something in the setState step.
I have tried to make it a function and also using variable.then(...).
I am using a for loop because there are hundreds of results in the api and i only want 10 of them.
this is my code:
const ResultadosScreen = props => {
const [results, setResults] = useState({});
useEffect(() => {
async function fetchData() {
const response = await fetch('apiUrlGoesHere');
// response.json().then((response => setResults(response)));
const resData = await response.json();
const pastResults = resData.past;
const loadedResults = [];
for (let r = 0; r < 11; r++){
loadedResults.push(
new FakeResult(
r,
pastResults[r].drawingDate.substring(0,10),
pastResults[r].nr,
pastResults[r].numbers
)
);
}
console.log(loadedResults); // I GET THE EXPECTED 10 ITEMS IN THIS CONSOLE LOG
(loadedResults => setResults(loadedResults)) //HERE IS WHERE IM MISSING SOMETHING
}
fetchData()
});
console.log(results);
//I GET UNDEFINED FROM THIS CONSOLE LOG
return (
<View style={styles.screen}><Text style={styles.headerTitle}>{}</Text></View>
);
};
export default ResultadosScreen;
Thanks for your help

Asynchronous controller in Express for Form parsing to Mongoose

Currently, I'm developing a way to upload a message (file and fields) from Dropzone to Mongoose using Express Router. My back-end controller (which is called after authentication and data validation) goes as follows:
//Import Internal Dependencies
const Loader = require('../models/loader.js');
const Formidable = require('formidable');
const fs = require('fs');
module.exports = {
load: async (req, res, next) => {
var form = new Formidable.IncomingForm();
let path;
let contentType;
await form.parse(req, async function (err, fields, files) {
if (err) {
return res.status(404).json(err);
} else {
const {
user,
patient,
condition,
compound,
classi
} = fields;
path = files.image.path;
contentType = files.image.type;
fs.readFile(path, async function (err, data) {
if (err) {
return res.status(404).json(err);
} else {
//Save load
const newLoader = new Loader({
user,
patient,
condition,
compound,
classi,
image: {
data,
contentType
}
});
//Delete image in local storage
await fs.unlink(path, function (error) {
if(error){
return res.status(404).json(error)
}
});
await newLoader.save();
res.status(200).json("Load image sucessfully.");
next()
}
})
}
});
}
};
When I test it with Postman I got a status 202 and images are successfully upload to the database. However, when I try to upload with dropzone without the fields (which should cause some error and be displayed in dropzone) I got the following errors/warning in the back-end console (Dropzone stoped at upload and didn't show any error):
(node:20834) UnhandledPromiseRejectionWarning: ValidationError: load validation failed: user: Path `user` is required., classi: Path `classi` is required.
at new ValidationError (/root/aimuneBack/node_modules/mongoose/lib/error/validation.js:27:11)
at model.Document.invalidate (/root/aimuneBack/node_modules/mongoose/lib/document.js:1876:32)
at p.doValidate.skipSchemaValidators (/root/aimuneBack/node_modules/mongoose/lib/document.js:1744:17)
at /root/aimuneBack/node_modules/mongoose/lib/schematype.js:808:9
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:20834) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20834) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
at emitWarning (internal/process/promises.js:92:15)
at emitPendingUnhandledRejections (internal/process/promises.js:109:11)
at process._tickCallback (internal/process/next_tick.js:189:7)
POST /load - - ms - -
So I know I have done something wrong with my asynchronous code and unfortunately cannot figure it out. Hope you can help. Best regards, Andre