expo app not fetching updates from publish - javascript

For some reason, I need to close and reopen the app multiple times and even clear my cache before my expo app updates.
After seeing this I went through the documentation for expo updates and I put this code in my App.js but I don't understand how can I force the expo app to update as soon as one is available
async componentDidMount() {
try {
const update = await Updates.checkForUpdateAsync();
if (update.isAvailable) {
await Updates.fetchUpdateAsync();
// ... notify user of update ...
await Updates.reloadAsync();
}
} catch (e) {
// handle or log error
console.log(`update his an error ${e}`)
}

Related

React: Component randomly doesn't refresh after state changes

I am working on a CRUD (express, mongoose, mongodb) which is mostly working as expected... except when it comes to rendering the entries after deleting X amount of them.
Not deleting
Sometimes I can delete 10 entries without any issues, until the component is empty, and other times I delete some entries and then the page just stop rending the updated data and enters an infinite loading state in the browser; only when I hard reload the browser the page renders the latest data, yet it does delete the entry , it just freezes it seems!
From React:
useEffect(() => {
queryClient.invalidateQueries(["allUsers"]);
});
const mutation = useMutation({
mutationFn: async (userid) => {
return await axios.delete("/api/deleteuser", { data: { userid: userid } });
},
});
const handleDelete = (userid) => {
mutation.mutate(userid);
navigate("/", { replace: true });
};
From Mongoose
const deleteUser = async (req, res) => {
try {
await newUser.findOneAndDelete({ userid: req.body.userid });
} catch (error) {
return error;
}
};
Tried invalidating the query cache at the delete function but the result is the same. It just happens randomly, as if the request was not fulfilled... in dev tools/network the request is never fulfilled but the data, whenever it does work, is updated.Network/pending
Edit: I'm using a mongoDB free account... I've read sometimes the response times are not the best, perhaps it is the reason?
useEffect without a dependency array is pretty pointless. It will run every time the component is rerendered.
I assume you are using react-query. Try moving your queryClient.invalidate to onSuccess or onSettled in your useMutation config object. This will ensure your query is invalidated only after the mutation is done.
https://react-query-v3.tanstack.com/guides/mutations#mutation-side-effects

NestJS Prisma: start application even if prisma can't connect to database

I'm trying to prevent prisma from from shutting my app down even if it fails to connect to the database, so that my health-check endpoint can still be reached. The error I get is this:
throw new PrismaClientInitializationError(error2.message, this.config.clientVersion, error2.error_code);
^
Error: Can't reach database server at `postgres`:`5432`
Please make sure your database server is running at `postgres`:`5432`.
at startFn (/home/my_name/my_folder/my-service/node_modules/#prisma/client/runtime/index.js:27186:17)
at Proxy.onModuleInit (/home/my_name/my_folder/my-service/src/services/prisma.ts:12:5)
which makes sense, because my database is shut off. But this crashes my nest application.
The prisma docs say that the PrismaClientInitializationError is returned whenprisma.$connect runs, or if a query is run.
The obvious solution to me was to wrap this.$connect with a try catch to prevent it from crashing and burning. So here is my attempt in my PrismaService - the file that the error above is complaining about my-service/src/services/prisma:
import { INestApplication, Injectable, OnModuleInit } from '#nestjs/common';
import { PrismaClient, Prisma } from '#prisma/client';
#Injectable()
export class PrismaService
extends PrismaClient<Prisma.PrismaClientOptions, 'query' | 'error'>
implements OnModuleInit
{
constructor() {
try {
super();
} catch (e) {
console.log(e);
}
}
async onModuleInit() {
this.$on('error', (event) => {
console.log(event.target);
});
try {
await this.$connect();
} catch (e) {
console.log(e);
}
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}
It's littered with console logs, and none of them log anything to the console. In fact, I found that even if I delete this.$connect if my database is up and running then prisma still connects to the database. If my database is not running I still get the same error message as above.
My question is, where do I need to put a try catch in order to prevent prisma from breaking my app?
And to satisfy my curiosity, why is the prisma client seemingly initializing itself even if I don't run this.$connect
This issue has seemingly resolved itself. and my error handling now works. I'm suspecting that because I was using docker compose with mounted volumes some sort of caching was getting in the way and not registering that I had put a try/catch there

Infinite loop using fetch() in a custom react hook

I am making my first custom hook,for now it should just send a GET request. This is the hook:
const useMyCustomHook = request => {
// I have a couple of useState() here
const sendRequest = async () => {
// I set the states here
try {
console.log("2) This log shows up.");
const response = await fetch(request.url);
console.log("This does NOT shows up.");
if (!response.ok) throw new Error('Something went wrong');
// I reset the states here
} catch(error) {
console.log(error);
}
}; // end sendRequest()
console.log("1) This log shows up.");
sendRequest();
console.log("3) This log shows up.");
return {infoFromTheStates}
};
And that's how I call it: (The actual url is a bit different)
const response = useSendRequest({url: 'https://react-http-b228c-default-rtdb.europe-west1.firebasedatabase.app/tasks.json'});
When I run the app I get an infinite loop and I get the logs in the order I named them: first I get 1) then 2) and 3), then again 1) and so on...
It's like I never arrive to get a response from fetch().
I don't even know if the problem is my understanding of async/await or of some React logic.
Anyone knows what's going on?
Each time the component runs, it calls this custom hook, which makes a fetch and then change the state, which makes the component run and it calls the hook and so on.
You need to use useEffect so that it will only run the fetch once:
change
sendRequest();
to:
useEffect(sendRequest, []);

NetInfo usage pattern in React Native

I'm trying to create a robust pattern in my React Native app so that if Internet connection is not there, I won't make API calls but display a "Connection lost..." message.
I created the following util function and trying to incorporate it into my API calls using fetch but it doesn't seem to hit the then block after getting a response.
Here's the function that checks the connection:
import NetInfo from "#react-native-community/netinfo";
export const isConnectedToInternet = () => {
NetInfo.fetch().then(state => {
return state.isConnected;
});
};
And here's how I'm trying to use it:
import { isConnectedToInternet } from '../my-utils';
export const someApiCall = () => {
isConnectedToInternet()
.then(result => {
if(result) {
return (dispatch) => fetch ('https://myapi/someendpoint', fetchOptionsGet())
.then(response => {
// Process data...
})
} else {
Alert.alert('No Internet connection!');
}
})
};
Any idea why I'm not hitting the then block or suggestions to make this a robust pattern?
If you want to have the then on your isConnectedToInternet you should then make it return a promise. Try something like this:
import NetInfo from "#react-native-community/netinfo";
export const isConnectedToInternet = () => {
return new Promise((resolve, reject) => {
NetInfo.fetch().then(state => {
resolve(state.isConnected);
}).catch(e => reject(e));
})
};
In mobile software, a best practice is to always try the remote API, and then handle the exception if there's no internet. The reachability APIs provided by iOS and Android are not always accurate - they need to poll to determine connectivity. So an app is better off always trying the fetch, even if it thinks the internet may be down, in case the device got connectivity restored since the last reachability check.
If you want to model some state that shows UI when the app thinks it's offline, you can do that using the NetInfo.addEventListener() function. There's a React hook for that too I think.

React Native Firebase transaction not working properly

I'm developing an App using React Native and Firebase Real-Time Database.
In the database, I have some data as below.
myRoot
|
|--myValue1: 0
|
|--myValue2: 2
Then, I want to increase those values by one and get the following result.
myRoot
|
|--myValue1: 1
|
|--myValue2: 3
For this, I used a function as follows.
myFunction = () => {
const myRef = firebase.database().ref('myRoot');
return myRef.transaction((data) => {
data.myValue1++;
data.myValue2++;
return data;
})
.then(console.log('Done'))
.catch((error) => console.log(error));
}
But, after calling the function, I get the following error.
[Unhandled promise rejection: TypeError: null is not an object (evaluating 'data.myValue1')]
I tried taking a snapshot of myRef and print it in the console. It worked and printed the current values. But, transaction does not work and gives null.
Please help me to solve this problem.
You'll need to check data for null, as this happens the first time the transaction handler function is called. The handler will get called again with the snapshot, if it's present at the location of the database where you are performing the transaction. You can see this check being performed in the sample code in the documentation.
Something like this I believe Sennen:
myFunction = () => {
const myRef = firebase.database().ref('myRoot');
myRef.transaction((data) => {
if(data) {
if(data.myValue1) {
data.myValue1++;
}
if(data.myValue2) {
data.myValue2++;
}
}
return data;
})
.then(console.log('Done'))
.catch((error) => console.log(error));
}
Found what caused the problem. The code segment is fine. The problem was in the dependencies. Just execute npm install firebase --save and then npm install. Restart the project. It worked!

Categories