I'm building a React Native app using Firebase. I use the following method (among others) in one of my components to get data from Firebase:
loadMessagesFromFirebase(chatId){
let messageList = [];
let data = {};
let message = {};
const dataRef = firebase.database().ref('chats').child(chatId);
dataRef.on('value', datasnap=>{
data = datasnap.val()
})
for (var sayer in data){
for (var m in data[sayer]){
message = {sayer: sayer, text: m.text, time: new Date(m.created)};
messageList.push(message);
}
}
messageList.sort((a,b) => (a.time > b.time) ? 1: -1);
this.setState({messageList: messageList});
}
The problem is that occasionally, data will load as an empty dictionary (Object {}) and therefore, the message list will be empty. I assume this happens because I'm not giving Firebase enough time to load. How do I make this function asynchronous, so that I can add a "loading" state to the component and not display message information until it's finished loading?
async componentDidMount(){
firebase.initializeApp(FirebaseConfig);
this.loadMessagesFromFirebase(this.state.chatId);
//once the messages are done loading
this.setState({{loading: false}})
}
Additionally, is there a way to make sure that, if data is returned as an empty dictionary, it's because Firebase finished loading and NOT because there isn't data for this chat id?
Answering this question even though OP seems to figured out the answer, since he hasn't explained the underlying concepts.
Firebase sdk uses async programming and observer pattern to provide real time updates.
The right way to Asynchronous Firebase data get on React Native world be as follows.
Initialize firebase sdk only once during application startup. In React terms this can be done inside the constructor of the top level App component.
See firebase docs for the steps. https://firebase.google.com/docs/database/web/start
Inside component constructor or componentDidMount set up the call to firebase function to load data
componentDidMount(){ this.loadMessagesFromFirebase(this.state.chatId); }
In the load messages function at up async call to the firebase realtor database. More reading here https://firebase.google.com/docs/database/web/read-and-write
The main thing to remember here is that all code that has to run after data is available has to be triggered from writing the async call back. Modifying the example code from the question
loadMessagesFromFirebase(chatId){
let data = {};
let output = {};
const dataRef = firebase.database().ref('chats').child(chatId);
dataRef.once('value', datasnap=>{
data = datasnap.val();
// Do something really smart with the data and assign it to output
......
output = data;
// set updates to the state
this.setState({output: output});
})
}
Note the use of once instead of the on function.
The reason for this is that for getting subscription to the observer on can lead to the callback being triggered every time there is a change in data. This can lead to undesirable consequences if the component was designed to only get data once.
Further reading https://firebase.google.com/docs/database/web/read-and-write
In case it is desirable to have the component updated every time there is a data change then use the on function to set up a subscription to that data. However in such a case it is important to cancel the subscription inside of componentWillUnmount
https://firebase.google.com/docs/reference/js/firebase.database.Reference#off
This can be summarized as follows
`
// inside componentDidMount
this.onValueChange = ref.on('value', function(dataSnapshot) { ... });
// Sometime later.... Inside componentWillUnmount
ref.off('value', this.onValueChange);`
Figured it out thanks to vvs' comment. Everything that has to be done asynchronously has to go into that dataref.on() function.
loadMessagesFromFirebase(chatId){
let messageList = [];
let data = {};
let message = {};
const dataRef = firebase.database().ref('chats').child(chatId);
dataRef.on('value', datasnap=>{
data = datasnap.val()
for (var sayer in data){
for (var m in data[sayer]){
message = {sayer: sayer, text: m.text, time: new Date(m.created)};
messageList.push(message);
}
}
messageList.sort((a,b) => (a.time > b.time) ? 1: -1);
this.setState({messageList: messageList});
this.setState({{loading: false}})
})
}
And this is how the function is called:
componentDidMount(){
this.loadMessagesFromFirebase(this.state.chatId);
}
(Having firebase.initializeapp(FirebaseConfig) in there actually causes problems- it has to run once, and earlier, such as when setting up the app)
Related
I have a store that fetches data once in a while – according to user's actions. This is a store because its data is used globally and mainly all components needs the latest data available.
But, for one specific component, I only need the first data loaded.
For this component, there is no reason to keep a subscribe() function running after the first fetch. So, how can I stop this subscribe function?
The only example in Svelte doc's uses onDestroy(), but I need to manually stop this subscribe().
I tried with a simple "count" (if count > 1, unsubscribe), but it doesn't work.
import user from './store'
let usersLoaded = 0
const unsubscribe = user.subscribe(async (data) => {
if(data.first_name !== null) {
usersLoaded = usersLoaded + 1
}
if(usersLoaded > 1) {
unsubscribe;
}
});
Here's a full working REPL:
→ https://svelte.dev/repl/95277204f8714b4b8d7f72b51da45e67?version=3.35.0
You might try Svelte's get. A subscription is meant for situations where you need to react to changes; it's a long-term relationship. If you just need the current value of the store, get is the way to go.
Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get allows you to do so.
import { get } from 'svelte/store';
const value = get(store);
I had to use unsubscribe() instead of unsubscribe 🤡
Here's the final working REPL with some improvements:
https://svelte.dev/repl/95277204f8714b4b8d7f72b51da45e67?version=3.35.0
You can use auto subscribe: $user which will also auto unsubscribe.
Some more details in the docs.
Example:
let user1 = null;
$: if ($user?.first_name && !user1) {
user1 = $user.first_name;
console.log('first user', $user.first_name);
}
And you do not really need a writable store here. You can use a readable and use the set method to handle the fetch.
Something like:
const user = readable(defaultUser, set => {
.... fetch the data ....
.... set(data)
}
By the way: This is already async code and you can use set(data) to store the fetch result.
Updated: 04 Jan 2023
Best way to unsubscribe is using onDestroy Svelte's hook
import { onDestroy } from "svelte"
const subcriber = page.subscribe((newPage) => handleChangePage(newPage.params.id))
onDestroy(subcriber)
I have a master page that is a list of items, and a details page where I fetch and can update an Item. I have the following hooks based upon the react-query library:
const useItems = (options) => useQuery(["item"], api.fetchItems(options)); // used by master page
const useItem = id => useQuery(["item", id], () => api.fetchItem(id)); // used by details page
const useUpdateItem = () => {
const queryClient = useQueryClient();
return useMutation(item => api.updateItem(item), {
onSuccess: ({id}) => {
queryClient.invalidateQueries(["item"]);
queryClient.invalidateQueries(["item", id]);
}
});
};
The UpdatePage component has a form component that takes a defaultValue and loads that into it's local "draft" state - so it's sort of "uncontrolled" in that respect, I don't hoist the draft state.
// UpdatePage
const query = useItem(id);
const mutation = useUpdateItem();
return (
{query.isSuccess &&
!query.isLoading &&
<ItemForm defaultValue={query.data} onSubmit={mutation.mutate} />
}
);
The problem is after I update, go to Master page, then back to Details page, the "defaultValue" gets the old item before the query completes. I do see it hitting the API in the network and the new value coming back but it's too late. How do I only show the ItemForm after the data is re-queried? Or is there a better pattern?
My updateItem API function returns the single updated item from the server.
I used setQueryData to solve this.
const useUpdateItem = () => {
const queryClient = useQueryClient();
// Note - api.updateItem is return the single updated item from the server
return useMutation(item => api.updateItem(item), {
onSuccess: data => {
const { id } = data;
// set the single item query
queryClient.setQueryData('item', id], data);
// set the item, in the all items query
queryClient.setQueryData(
['item'],
// loop through old. if this item replace, otherwise, don't
old => {
return old && old.map(d => (d.id === id ? data : d));
}
);
}
});
};
I will say, react-query is picky about the key even if it is fuzzy. Originally my id was from the url search params and a string, but the item coming back from the db an int, so it didn't match. So a little gotcha there.
Also, when I go back to the Master list page, I see the item change, which is kind of weird to me coming from redux. I would have thought it was changed as soon as I fired the synchronous setQueryData. Because I'm using react-router the "pages" are complete remounted so not sure why it would load the old query data then change it.
isLoading will only be true when the query is in a hard loading state where it has no data. Otherwise, it will give you the stale data while making a background refetch. This is on purpose for most cases (stale-while-revalidate). Your data stays in the cache for 5 minutes after your detail view unmounts because that’s the default cacheTime.
Easiest fix would just set that to 0 so that you don’t keep that data around.
You could also react to the isFetching flag, but this one will always be true when a request goes out, so also for window focus refetching for example.
Side note: invalidateQueries is fuzzy per default, so this would invalidate the list and detail view alike:
queryClient.invalidateQueries(["item"])
I had the same issue today. After scanning your code it could be the same issue.
const useItem = id => useQuery(["item", id], () => api.fetchItem(id)); // used by details page
The name of the query should be unique. But based on you details the ID changes depends on the item. By that you call the query "item" with different IDs. There for you will get the cached data back if you have done the first request.
The solution in my case was to write the query name like this:
[`item-${id}`...]
I'm trying to build a component that retrieves a full list of users from Amazon AWS/Amplify, and displays said results in a table via a map function. All good so far.
However, for the 4th column, I need to call a second function to check if the user is part of any groups. I've tested the function as a button/onClick event - and it works (console.logging the output). But calling it directly when rendering the table data doesn't return anything.
Here is what I've included in my return statement (within the map function)
<td>={getUserGroups(user.email)}</td>
Which then calls this function:
const getUserGroups = async (user) => {
const userGroup = await cognitoIdentityServiceProvider.adminListGroupsForUser(
{
UserPoolId: '**Removed**',
Username: user,
},
(err, data) => {
if (!data.Groups.length) {
return 'No';
} else {
return 'Yes';
}
}
);
};
Can anyone advise? Many thanks in advance if so!
Because you should never do that! Check this React doc for better understanding of how and where you should make AJAX calls.
There are multiple ways, how you can solve your issue. For instance, add user groups (or whatever you need to get from the backend) as a state, and then call the backend and then update that state with a response and then React will re-render your component accordingly.
Example with hooks, but it's just to explain the idea:
const [groups, setGroups] = useState(null); // here you will keep what "await cognitoIdentityServiceProvider.adminListGroupsForUser()" returns
useEffect(() => {}, [
// here you will call the backend and when you have the response
// you set it as a state for this component
setGroups(/* data from response */);
]);
And your component (column, whatever) should use groups:
<td>{/* here you will do whatever you need to do with groups */}</td>
For class components you will use lifecycle methods to achieve this (it's all in the documentation - link above).
what i want to do is dispatch an action in my set interval function and not in get initial props and save my data in store and how to get that data back from store in react app it was simple just import action form action file and call like this this.props.actionName() but how do i do this in next and to get data from store we map state to props how can it be done in next thanks here my function which i want to implement in
this.fetchCryptoData().then(data => {
var Keys = Object.keys(data.DISPLAY);
this.setState(
{
crypto_head_coins: Keys
},
() => {
// // this.props.update_array([]); // update_array() is my action i haven't imported it
let rate_updated = [true, true, true, true]; // i want my store updated_array data here
for (let i = 0; i < this.state.crypto_head_coins.length; i++) {
//my code here
// this.props.store.dispatch(update_rate_array(rate_updated)) //it says cant read property
// of dispatch of undefined
// i want to dispatch my action here not in getinitialprops
this.setState({ rate_updated });
}
);
});
I use NextJS sometimes, It is the same as a Create-React-App essentially.
I just noticed your question does not include 'React-Redux', You will need to install/save 'React-Redux' and 'Redux' to use connect/dispatch, etc. I have a sample boilerplate on Github.
Another missing piece for converting this into an action.. is perhaps redux-thunk, to handle promises.(Try without it first.)
More information on redux-thunk here.
https://github.com/reduxjs/redux-thunk
You are setting state twice(once in the callback of another), which is going to cause multiple re-renders. (Unless ShouldComponentUpdate is implemented) Might want to re-consider this design.
Implement your MapDispatch to Props
After doing so you can simplify the line calling it, like the below using destructing.
// this.props.store.dispatch(update_rate_array(rate_updated)) //it says cant read property
let update_rate_array = {this.props}
update_rate_array(rate_updated)
You should implement your MapDispatchToProps removing some complexity in the naming and calling.
I have uploaded some simple examples to Github, and there is also an identical related CodeSandbox.
To receive your updated information from State, use MapStateToProps.
Example here.
What is the current idiomatic way to lazy load properties when using MobX?
I've been struggling with this for a few days, and I haven't found any good examples since strict mode has become a thing. I like the idea of strict mode, but I'm starting to think lazy-loading is at odds with it (accessing, or observing a property should trigger the side effect of loading the data if it's not already there).
That's the crux of my question, but to see how I got here keep reading.
The basics of my current setup (without posting a ton of code):
React Component 1 (ListView):
componentWillMount
componentWillMount & componentWillReceiveProps - the component gets filter values from route params (react-router), saves it as an observable object on ListView, and tells the store to fetch 'proposals' based on it
Store.fetchProposals checks to see if that request has already been made (requests are stored in an ObservableMap, keys by serializing the filter object so two identical filters will return the same response object). It makes the request if it needs to and returns the observable response object that contains info on whether the request is finished or has errors.
ListView saves the observable response object as a property so it can display a loading or error indicator.
ListView has a computed property that calls Store.getProposals using the same filter object used to fetch
Store.getProposals is a transformer that takes a filter object, gets all proposals from an ObservableMap (keys on proposal.id), filters the list using the filter object and returns a Proposal[] (empty if nothing matched the filter, including if no proposals are loaded yet)
This all appears to work well.
The problem is that proposals have properties for client and clientId. Proposal.clientId is a string that's loaded with the proposal. I want to wait until client is actually accessed to tell the store to fetch it from the server (assuming it's not already in the store). In this case ListView happens to display the client name, so it should be loaded shortly after the Proposal is.
My closest I've gotten is setting up a autorun in the Proposal's constructor list this, but part of it is not reacting where I'm indending. (truncated to relevant sections):
#observable private clientId: string = '';
#observable private clientFilter: IClientFilter = null;
#observable client: Client = null;
constructor(sourceJson?: any) {
super(sourceJson);
if (sourceJson) {
this.mapFromJson(sourceJson);
}
//this one works. I'm turning the clientId string into an object for the getClients transformer
autorun(() => { runInAction(() => { this.clientFilter = { id: this.clientId }; }) });
autorun(() => {
runInAction(() => {
if (this.clientId && this.clientFilter) {
const clients = DataStore.getClients(this.clientFilter);
const response = DataStore.fetchClients(this.clientFilter);
if (response.finishedTime !== null && !response.hasErrors) {
this.client = clients[0] || null;
console.log('This is never called, but I should see a client here: %o', DataStore.getClients(this.clientFilter));
}
}
})
});
}
The response object is observable:
export class QueryRequest<T extends PersistentItem | Enum> {
#observable startTime: Date = new Date();
#observable finishedTime: Date = null;
#observable errors: (string | Error)[] = [];
#observable items: T[] = [];
#computed get hasErrors() { return this.errors.length > 0; }
#observable usedCache: boolean = false;
}
I'm getting the feeling I'm fighting the system, and setting up autoruns in the constructor doesn't seem ideal anyway. Anyone solve this pattern in a reasonable way? I'm open to suggestions on the whole thing if my setup looks crazy.
EDIT 1: removed #Mobx for clarity.
EDIT 2:
Trying to re-evaluate my situation, I (again) found the excellent lib mobx-utils, which has a lazyObservable function that may suite my needs. Currently it's looking like this:
client = lazyObservable((sink) => {
autorun('lazy fetching client', () => {
if (this.clientFilter && this.clientFilter.id) {
const request = DataStore.fetchClients(this.clientFilter);
if (request.finishedTime !== null && !request.hasErrors) {
sink(request.items[0]);
}
}
})
}, null);
This is working!
I think I need the autorun in there to update based on this objects clientId/clientFilter property (if this object is later assigned to a new client I'd want the lazyObservable to be updated). I don't mind a little boilerplate for lazy properties, but I'm, definitely open to suggestions there.
If this ends up being the way to go I'll also be looking at fromPromise from the same lib instead of my observable request object. Not sure because I'm keeping track of start time to check for staleness. Linking here in case someone else has not come across it:)
I've been using a different approach in my projects and I extracted it into a separate npm package: https://github.com/mdebbar/mobx-cache
Here's a quick example:
First, we need a React component to display the client info:
#observer
class ClientView extends React.Component {
render() {
const entry = clientCache.get(this.props.clientId)
if (entry.status !== 'success') {
// Return some kind of loading indicator here.
return <div>Still loading client...</div>
}
const clientInfo = entry.value
// Now you can render your UI based on clientInfo.
return (
<div>
<h2>{clientInfo.name}</h2>
</div>
)
}
}
Then, we need to setup the clientCache:
import MobxCache from "mobx-cache";
function fetchClient(id) {
// Use any fetching mechanism you like. Just make sure to return a promise.
}
const clientCache = new MobxCache(fetchClient)
That's all you need to do. MobxCache will automatically call fetchClient(id) when it's needed and will cache the data for you.