ReactNative: AsyncStorage not working properly - reactjs

Hello I am trying to impliment a login and the most of the logic is inside action creator but for some react my code doesn't execute after
await AsyncStorage.setItem('adminFlag', adminFlag);
await AsyncStorage.setItem('token', token);`
the console.log(data) is working before this statement...I have no idea why this is happening
export const verifyPassword = (
adminFlag,
password,
navigate
) => async dispatch => {
loadingStatus(dispatch, true);
try {
const { data } = await axios.post(
"myurl with response success--lajja--token",
{
admin: adminFlag,
job: "verifyPassword",
password
}
);
if (data.includes("--lajja--")) {
//spliting the token and the response
const destructuredData = data.trim().split("--lajja--");
const response = destructuredData[0];
const token = destructuredData[1];
console.log(data);
await AsyncStorage.setItem("adminFlag", adminFlag);
await AsyncStorage.setItem("token", token);
navigate();
loadingStatus(dispatch, false);
}
loadingStatus(dispatch, false);
} catch (e) {
console.log(e);
loadingStatus(dispatch, false);
}
};
the lines after console.log(data) are not working...

The problem happened to me as well as to some people on this issue. This seems to happen on Android devices (only during debug) that are running some background activities as specified here and here. The pull request provided by #github/jsdario to fix that issue seems to have not passed the CI though. I guess for now we have to debug... Without the debugger attached.

Related

I have CORS error even if I enable it on nest server

Hey I think the problem in my code is on the frontend react cod because if I use Postmap my api on nest works correct.
What I have to do: I'm checking on the backend if the input phare is correct. If yes it will answers to the post request sending an object contained urls of images than I will render.
In my console log when I try to post the request I have the attached image error:
This is my function that handle the request:
const getImages = async (secret) => {
try {
const response = await axios.post('http://localhost:5000/secret', {secret});
return response.data;
} catch (error) {
console.log(error);
}
}
const handleSecret = async (e) => {
secret = phrase;
console.log(secret)
if (e.key === "Enter" || e.type === "click") {
const images = await getImages(secret);
if (images) {
//render image if true
setSecret(true);
} else {
window.alert("Incorrect phrase");
setSecret(false);
}
}
}
I need community help!
I have already enable cors on nest backend:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(5000);
app.enableCors();
}
bootstrap();
You need to enable cors before using app.listen(). Think of regular express middleware, anything after app.listen() doesn't get bound to the server, it's the same thing here

Why do I keep getting Syntax Error: JSON parse even though my code works with another API?

Working with React and I continually get a SyntaxError:JSON.parse when I try to fetch from the API. I'm able to fetch the data just fine when working with a different API.
What am I doing wrong here? I'm a complete newb when it comes to API's so please don't eviscerate me if this is a stupid question :D
const API_URL = 'www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
const getMealRequest = async()=>{
const response = await fetch(API_URL)
const data = await response.json()
console.log(data)
}
useEffect(()=>{
getMealRequest()
},[])
There is an error on your API call which is not related to this question. You didn't implement try/cath block with the getMealRequest so in the failure case, the response is not a valid object to parse and you get the mentioned error.
To solve it:
const getMealRequest = async () => {
try {
const response = await fetch('https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata'
)
const data = await response.json()
console.log(data)
} catch (error) {
console.log(error)
}
}
Now inspect your console and see what is wrong with your API call. also, you can check the network tab for further detail about the request and response on calling API_URL.
const API_URL = 'https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
const getMealRequest = async() => {
const response = await fetch(API_URL)
const data = await response.json()
console.log(data)
}
getMealRequest()
You forgot to include protocol:
incude https:// before the address and it will work:

Getting Error Response using axios on Client Side in React

I am learning react. I have written backend code as follows.
router.post('/signup', async (req,res)=>
{
try
{
const user = new User(req.body);
const token = await user.generateAuthToken();
res.cookie('authToken', token);
res.status(201).send();
}
catch(err)
{
res.status(400).send({err: "User Already Exists"});
}
})
on fontend, I am using axios to send request. my code is as follows.
e.preventDefault();
try
{
const res = await axios.post("/signup",{email, password});
}
catch(err)
{
console.log(err)
}
My Question is how can I get User Already Exists this statement from backend in case of error.
In case of any response other than 2xx from backend, the catch block runs on frontend and we can get data using err.response object. To get data, use the following code
try
{
const res = await axios.post("/signup",{email, password})
console.log(res.data)
}
catch(err)
{
if(err.response)
{
console.log(err.response.data)
}
}
Something else broke your function and you have to debug what is wrong here:
catch(err){
console.log(err)
res.status(400).send({err: "User Already Exists"});
}

Login status in React

I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399
Then in React I get userId by using the passed url parameter => phoneNumber using axios.
I realized it in App.js. Code below:
let url = window.location.href;
let params = (new URL(url)).searchParams;
const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
const [userToken, setUserToken] = useState(null);
const getUserToken = async() => {
try {
const data = await axios
.get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
.then(response => {
setUserToken(response.data);
})
.catch(function(error) {
console.log('No such user! Error in getting token!');
});
} catch (e) {
console.log(e);
}
}
useEffect(() => {
getUserToken();
console.log(userToken);
}, userToken);
So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.
How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.
If you want to do that without using any third party libraries you can use browser's in built storage api
So, when you receive the token, you can store that in the local storage of the browser using localstorage.setItem and later when you wan to see if the token is there or not just read from there using localStorage.getItem
const getUserToken = async() => {
try {
const data = await axios
.get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
.then(response => {
setUserToken(response.data);
Storage.setItem('token',JSON.stringify(response.data))
})
.catch(function(error) {
console.log('No such user! Error in getting token!');
});
} catch (e) {
console.log(e);
}
}
For Logout you can simply remove the token using localStorage.removeItem
You can easily achieve this by using the react-cookie library
npm i react-cookie
Can be easily implemented in your code by
cookies.set('key', value, { path: '/' });
cookies.get('key')
After getting the userNumber form the param
const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
cookies.set('userphoneNum', userPhoneNum);
View the documentation for more information
https://www.npmjs.com/package/react-cookie

An array from a NodeList while scraping with Puppeteer doesn't appear

I'm trying to scape a website but I cannot find a way to show the results in the console.log.
The script I've created is the following:
const puppeteer = require("puppeteer");
(async () => {
try {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto(`https://www.coches.net/nuevo/km-0/`);
await page.waitFor(4000);
const news = await page.evaluate(() => {
const urlsArray = Array.from(document.querySelectorAll('.mt-CardAd-link')).map(a => a.href);
return urlsArray;
});
console.log(news);
await browser.close();
console.log("Browser Closed");
} catch (err) {
console.log(err);
await browser.close();
console.log("Browser Closed");
}
})();
While the variable urlsArray works in the devconsole of Chrome, it doesn't when launching the script in the terminal with the previous script. I tried everything but I don't find anything to solve this issue.
What I can do to finally be able to show this array with the console.log?
Thank you!
Your script seems to be fine, but the page you´re trying to enter is examinating the cookies and blocking your script's access.
I believe you should take a look at this:
How to avoid being detected as bot on Puppeteer and Phantomjs?

Resources