What is the best way to fetch data only once in react? - javascript

so let's say I have a react dashboard application, which has several different routes. Now, one of those routes is Analytics route, and I was wondering, if is, what is the best way to fetch the data rendered in Analytics route only the first time you visit it and then pull it from somewhere.
I've been thinking about using Redux for it, but I've never used it, so I have no idea, OR if I should store it in localStorage. But that has a problem though, because on different route, I would like to fetch images the same way.
The reason I'm asking this is because I use Firebase Firestore as my DB and it could get quite costly, because I would have to do 4 read operations i.e. on the Analytics route each time it is rendered. Or, is it the normal approach?
Is it a good idea to use React Context and useContext hook in this case?
Thanks in advance.

use redux for state management, where you can store the application state and the components who need data. You can call Api in order to fetch data only first time in the root component of the app.

use react-query you can do exactly this in a much simpler way as compared to context or react-redux.

you can use a useEffect hook and do an api call each time you visit that page and you don't have to store it anywhere and it will only get you the date you need i recently made an app and this way actually helped me alot

Related

Standard component interaction mechanisms vs Vuex - how to combine them?

The question is probably more theoretical.
I have little experience with Vue and am trying to figure out where my knowledge gaps are and fill them.
There are standard mechanisms for interaction between components:
from top to bottom - input parameters (props) are passed from parent components to child components
from bottom to top - events are thrown from child to parent
And on the other hand, there is VUEX with its own data storage, which is, roughly speaking, a global variable object with a set of methods for working with it.
Data from this storage is available at any time to any component. And it turns out that the use of Vuex seems to make the standard interaction mechanisms of components completely unnecessary.
Well, perhaps, the generation of events is still needed so that one component can quickly make it clear to the other about the completed action, events, etc.
The question is, does Vuex generally override the standard component interactions?
If it is not, how should it be combined in the right way?
I'll try to answer your question.
Vuex will be very usefull to store data that you'll need in a part of the application or globally, like user data.
If you can simply use $emit or props use it, it will be better and simple to understand the code, because it will be overkill to use the store just for "a prop".
So, you will use Vuex in your component to call an action and fetch / store some data you will need in a another view out of your children/parents context.
I don't know if my explanations are well haha, I tried :)

Making api calls from React component using Redux

I have got one question which bothers me a lot when I work with React and Redux. In my application I have my own API middleware for making api calls using plain actions. It makes fetch under the hood and returns Promise, works great. But sometimes I have a feeling that data I would like to get does not fit in my store and should not be there ex. it is only important for single component and shouldn't be global.
What do I mean exactly, this is how I normally do data fetching. I make an action creator like this:
dispatch(apiCall({ url, type, typePrefix })
typePrefix is prefix for request, success and failure actions ex. ${typePrefix}/REQUEST. After that I can react to these actions in my reducer.
Now, sometimes I am thinking about just making fetch in my provider/container component, save it to local state and pass it down to presentational component.
When I use Redux are thunks (or sagas) an only way to perform data fetching or is it fine to sometimes keep fetched data locally? I haven't found any question about it.
Quoting from one of the creators of Redux:
I would like to amend this: don't use Redux until you have problems with vanilla React.
Redux is mainly required if you are finding it cumbersome to :
Pass same state across nested children.
Maintain multiple copies of same information across several components.
But if you feel redux is just complicating stuff, you should just stick to vanilla React and JS.
More on that can be read here.

Can componentDidMount share data between pages?

I am still learning React and I apologize if this is a stupid question. I am currently planning about the architecture of my simple App.
I am using Next.js for this project
I have a component that calls the third party API for data every 5 seconds. The data is shared among all pages in the app.
If the component that is fetching the data is not on the main/home page. Are there anyways for homepage to get the data it needs from another page?
For example [Below are all pages]
index.js // Plain simple page that displays current weather and top music
http://localhost:3000/
weatherforecast.js //Using componentDidMount every 5 seconds to fetch Weather Data
http://localhost:3000/weatherforecast
musicplaylist.js //Using componentDidMount every 5 seconds to fetch Weather
http://localhost:3000/musicplaylist
The data shown in homepage has to be refreshed every 5 seconds if there are changes to the following data in weatherforecast.js and musicplaylist.js
I had this in mind but I have a feeling that it's not the right way to do it.
In the Homepage.js, include WeatherForecast and MusicPlaylist components to fetch the data. If this is the case, it seems like I am repeating the same principle in every page.
I found out about Redux which store states as a global object. But how does the state know when to update. But before we getting to state, I am still not sure if components on another page can fetch the data without the user accessing the page.
Thanks for reading this question.
For a pure React solution, you need to utilize other lifecycle methods available for React. componentDidMount is a good spot for making API requests, so you're in the right place to start. However, componentDidMount occurs only once, right after the componentWillMount and after the DOM is ready with a complete render of the component. Setting your API call to run at a set interval will not trigger a rerender of the component, no any of it's sub components. Instead, use componentWillRecieveProps to add your interval request logic. After each interval completes, run setState with the new data from the request to update the default state defined in your constructor. As a bonus step to improve performace, follow up with function that returns a bool in componentShouldUpdate. This way you can strictly define how and when and what is causing any and all component re-rendering.
Redux is an excellent solution to take care of what you want to do. Personally always use it in my React projects to manage state. Using Redux, you could make your API calls still occur in componentDidMount, however the call can hook into your Redux store and update your initial state. The frees you up from have to worry about the local state of your component and how to go about conditionally rendering everything else in your app. Plus Redux abstracts other functions you need, like re-running your fetchToAPI in certain intervals, into their own source (known as Action Creators). Action Creators hook directly in the Redux store so that when one is used, the resulting state diff is passed to Redux's Reducers, which in turn update the application global state. Then all that needs to be done is to have all of your components that need re-rendering on global state change to listen for state changes that occur in the Redux store and conditionally re-render based on the diff of the store from prevState => newProps. This can be setup fairly easy using the boolean check in componentShouldUpdate.
Hope this helps! Cheers.
Redux passes the data throughout the connected components via prop, given that a component is mounted whenever it receives new props a new render cycle is initiated so it will reflect your changes, moreover if you dont want to use Redux you can try using the new context api which is easy to implement and will also be suitable for your solution here is a tutorial on how to use it
To pass data between pages in next.js you will have to use Redux. The idea of Redux is to have a single source of truth. In redux you update the state by calling actions. To update redux state you have to create something called action creators which dispatches action to update the state.
Answer to your question as to if components on another page can fetch data without the user accessing the page is that they do not need to access the data. The components are mounted only when they are accessed, so it will fetch the data when they are mounted.
Regarding the state change notification, refer to below image, and hopefully it is worth one thousand of words:
Original article here.

Proper Redux usage general questions

Im a little uncertain as to how Redux ties in with React ( without using the ReactRedux library ). Assume the following component structure
App
--TodoListController
----SomeComponent1
----TodoList
------TodoItem
--ProfileController
Question 1. Which components should listen for changes?:
Im assuming that the proper component to subscribe for state changes in the redux main (and only ) store should be the TodoListController and the ProfileController respectively ( essentially the non presentation components ).
Is this correct to assume or should all components listen to the state and render whatever is of interest to them? I essentially dont know which component should listen to state changes and am only guessing at this point
Question 2. Handling network calls:
I know this is to be examined per case but ill mention it anyway. Currently im handling network calls in the following manner:
A) When TodoListController mounts i get the state from the mainstore and also initiate a request to the server for the latest data. I also listen for changes in the store. So in practice:
class TodoListController extends React.Component{
componentWillMount(){
mainStore.subscribe()
getDataFromServer(function(data){
mainStore.dispatch(data)
})
}
getDataFromStoreAndUpdate(){
this.state.datawecarefor = mainStore.todoReducer.data
//set the state here to trigger a rerender
}
componentWillUnmount(){
mainStore.unsubscribe()
}
render(){
//render whatever component here that uses this.state.datawecarefor
}
}
Do you see any obvious flaws with this approach? I dont know what i dont know at this point.
Question 3. Where should store related helper functions live?
I currently have a reducer that holds all todolists for various users. Currently, when the redux store state updates i retrieve all this data and iterate through it to find the user im interested in. This shouldnt be in the controller itself but as a hepler function. I thought of creating a wrapper around the Redux store and it's reducers to create functions like getTodoListForUser(userId) but i dont know if thats the right approach. How do you handle logic like that?
P.S: Many people will point out that i should use the ReactRedux library that comes with many optimisations and they re probably right. This however isnt a production project, only one im trying to put together to better udnerstanding the core of both these two libraries before moving to something more optimal.
I know you don't want to use ReactRedux, but luckily enough there is a video of Dan Abramov explaining the source code. You should watch it, it will explain why they did what they did and how they did it. When I was first learning how redux and react worked together it made every so much more clear (and then I used ReactRedux anyway :)).
https://www.youtube.com/watch?v=VJ38wSFbM3A
There has been a lot of debate on where to connect React App's to the redux store. But it's mostly recommended that you want to connect where it makes logical sense. For example, if you have a container component that holds a bunch of comments, you don't need to connect all of the comments, you can just connect the container. In the same light you don't just want to connect your entire app at the top because then its more expensive to diff and update your app.
On another note you should probably try to handle network calls in redux middleware and dispatch an action your react component catches to cause a render.

Ember.js - How share route model-data between more routes? - Why not load data in component?

TL;DR
Embers components are just smart HTML-Templates. Why they don't fetch their data for themselves like Angular? And how I can share route models over more URLs/pages. It seems that I have to know wich components are placed on which URL and I have to make them the data available over the route models. Why is this part not in the component?
I learn at the moment Ember.js. I try at least.
At the moment I have a strong problem to understand why Ember.js acts like it does. Please correct me if I am wrong at some statements. I am an Ember.js beginner. So maybe its not right what I point out here.
Lets say we have a Request on / then Ember tries to find a route model in app/routes/index.js this file contains the code which data I want to fetch from the backend. Next Ember will render app/templates/index.hbs in this file I have a component called car-list.
As far no problems but let us have a closer look. For me it feels very weird that I have to fetch at first the data by myself, why the component doesn't do this on its own? Next problem is then how can I share the model fetch logic between more routes? Maybe I want to place my component on many URLs/pages/routes then I have to copy the route model logic?
In my opinion, the component should fetch the data by itself, that you can easily insert the component on other pages without copy the whole route model fetch logic.
So I have to know wich components are placed on which URL and I have to make them the data available over the route models. Why is this part not in the component?
So maybe I am just not good enough with Ember and I just overlook something?
Components are very flexible. Components have made to be reusable. For example you can create a table component and use for cars, ships, etc.
So for reusability it's better you separate model providing from component.
But if you want to make a component which is for current project and need to fetch its data itself, you can fetch data in the component.
In some scenarios you might want to fetch data in routes. For example in your page you have multiple components and every component needs a projection of data model which fetched in route.
So it depends on your requirements, maybe you need to fetch data in component or in route or even both (mixed)
Components certainly can load their own data, and in many cases that is appropriate. But allowing the route to load the data has several important benefits that you get "for free" if you stick to that pattern:
your application's URL will always reflect the state of the data. You don't have to remember to synchronize it (in both directions -- changes to URL should change the data, and changing the data should change the URL).
you can write your templates knowing that they won't render until the data is present, allowing Ember to handle the asynchrony for you. This results in cleaner, simpler templates.
you get Ember's built-in error handling for when the data fails to load.
A username component that appears on many pages typically belongs fairly high in the route hierarchy anyway, like in the application template, where it's easy to load & render it once from a single place and have it remain visible on every child route.
But if you do need to use a component in many places and its data should be self-contained, it's fine to let it do its own loading. In that case you can either rely on Ember Data's store to give you cached responses (so you only trigger a network request the first time) or write a Service that handles some persistent state for your component.

Categories

Resources