Correct way to share one query result throughout the app - reactjs

Let's say at the top of the app, we retrieve some basic information about the app or user before rendering the rest of the application:
const getUser = gql`
query getUser(id: Int!) {
user(id: $id) {
id
name
}
}
`)
function App({ data }) {
return (
<div>
{!data.loading && !data.error && (
// the application
)}
</div>
)
}
export default graphql(getUser, {
options: (props) => ({ variables: { id: props.id }})
})(App)
Now anywhere in the application, it is safe to assume that the user has been loaded and is stored. What is the proper way for another deeply nested component to the retrieve the user data without having to redo the querying and loading logic?

This is the very basic use of a store-based library like Redux. This is not the purpose to guide every step of the way here but you are looking for a single source of truth as described here: http://redux.js.org/docs/introduction/ThreePrinciples.html
In short:
Receiving getUser response should trigger a 'LOGGED_IN' action dispatching user Data, this would be catched by a reducer updating the user object in your store (as much nested as you want), a container would then connect to this user in the store and have all its data using connect()

As of now, I'm not certain there is a proper way, but these are the options I think are reasonable
Manually pass down data via props
Wrap your deeply nested component with the same query
Manual pass down ensures your components rerender correctly, but it can be a pain to refactor. Wrapping your nested component would just hit the cache. Yes, you probably need to redo the loading logic, but that's not a show stopper.
My advice is to manually pass down props for shallow nested components and rewrap deeply nested components. Unfortunately, react-apollo doesn't provide a convenient way to access the apollo-store for nested components the same way that redux's connect container does.

Related

Accessing cached data in RTK Query(new)

Imagine we have 3 component.
first is index which is parent.
second is filter component and third one is table component.
I used mutations for filter some data and show them in table.
In filter component I did this:
const [filterSomeData] = useFilterSomeDataMutation();
const data = filterSomeData(myFilter);
Now I need to access data in table component.
Redux toolkit query with every request cache the result , how can I access that?
Generally: If you are receiving data from the server without triggering a change on the server, you should be using a query, not a mutation. Yes, you can do POST requests with Queries and the syntax is 100% the same as with mutations.
Then you should be using that useQuery hook in all components that need that data, with the same argument as you passed in initially. That means if you have something like a filter, that you should either pass that filter in by props (by lifting the filter state up to a common parent) or keeping that filter in a Redux slice and getting it from Redux before calling your query hook.
Since you are calling that useQuery hook with the same argument in multiple components, it will not make multiple requests, but reuse the response of the first request.
What you need is api.endpoints.foo.useLazyQuery() or api.useLazyFooQuery(). This way you can assess the last fetched data on that endpoint.
Read more from the official doc: https://redux-toolkit.js.org/rtk-query/api/created-api/hooks#usequerystate
As in RTK documentation is explained, the proposed solution is calling useQuery hooks with the same arguments as before it called. It retrieves data from cached enpoints, But as I need too many arguments to send to query hook, and I should send it to other component, so I prefer to use the store object to access data from endpoints as below:
const store = useStore();
const cachedQueries = store.getState().dashboardApi.queries;
Then I made an object with endpoint's name as key and their data as value:
let dashboardResult: { [key: string]: any } = {};
Object.values(cachedQueries).forEach((item: any) => {
dashboardResult = {
...dashboardResult,
...{ [item?.endpointName]: item?.data?.data }
}
});

React GraphQL Apollo - how to fetch multiple times at once

I have a component which fetches data with one query with a parameter. I'd like to make this component call this query twice, with different parameters based on props (so maybe later even more-times). How can I achieve this? This is example of my code:
...
const getUser = gql`
query getUser($last_name: String!, $first_name: String!) {
user(last_name: $last_name, first_name: $first_name) {
id
last_name
first_name
}
}
`
export default graphql(
getUser, {
options: (props)=>{
return {
variables: {
last_name: ...something from props,
first_name: ...something from props
}
}
}
})(ComponentClassName)
Usually I fetch the appropriate user based on the props. That's ok. But now, I'd like to use this component and be able to fetch more users, without changing backend and much frontend. At least I need to be able to define through props which users to fetch, and if one or more. How can I do this? Thanks.
It sounds like you're using this component (let's call it User) as part of another one that has a list of users (let's call it UserList).
I see two solutions here:
If the UserList queries the list of users and gets their username which is later passed as a prop to each one of the User components and you can still use your getUser query. For performance reasons, and since you are using Apollo, it's probably a good idea to enable batching (https://dev-blog.apollodata.com/query-batching-in-apollo-63acfd859862), as you'll make one query per user.
You get all the data needed for each individual User in UserList and then pass it down as props. No queries would be made within each User component.
Hope that helps!
I think what you're looking for here is compose. With it, you could perform multiple graphql operations on one component. I implemented one here, which i composed both a query and a mutation.
You would be able to use it to compose two queries together, since they both have different props as mentioned.

Generic Components with React Redux

I am struggling a bit with the concept of global state and reusable components in redux.
Let's say I have a component that's a file-selector that I want to use in multiple places inside my applications state. Creating action/reducers leads to a lot of bloat as I have to handle states with dynamic suffixes and other weird things that just don't really strike me as a smart way to go about things.
What's the general consensus on these things? I can only see two solutions:
Make the file-selector component have local state (this.setState/this.getState)
Make the file-selector be part of the global state but in it's own unique reducer that I can read from once the operation of the component is done?
Any ideas / best practices? Thanks.
Update: To clarify the file selector I am describing is not a simple component that works purely on the client side but has to fetch data from the server, provide pagination as well as filtering etc.. That's why I'd also like to reuse most of the client/server interaction. The views that display this component are of course dumb and only display values from the state - but how do I reuse the actions/reducers in multiple places around the application?
Have your reducer handle multiple instances of your component state. Simply define some "unique" ID for each instance of your FileBrowser component when it appears in the app, and wrap your current state in an object with this uniqueIds as keys, and your old complex state as value.
This is a technique I've used multiple times. If all your FileBrowser are known at compile time, you can even setup the initial state before running your app. If you need to support "dynamic" instances, simply create an Action that initializes the state for a given id.
You didn't provide any code, but here's a contrived example for a reusable Todo reducer:
function todos(state={}, action){
switch(action.type){
case 'ADD_TODO':
const id = action.todoListId
return {
...state,
[id]: {
...state[id],
todos: [ ...state[id].todos, action.payload ]
}
}
// ...
}
}
Usually, the rule of thumb is that you use a redux store to manage data in your application aka storing items fetched from the server and local react state for ui behaviors, like file uploads in your case. I'd make a pure react component to manage file uploads and then use redux-form to manage specific form.
Here is the example of the component I use in my project
import React, {Component, PropTypes} from 'react';
import Button from 'components/Button';
class FileButton extends Component {
static propTypes = {
accept: PropTypes.string,
children: PropTypes.any,
onChange: PropTypes.func.isRequired
};
render() {
const {accept, children, onChange} = this.props;
return <Button {...this.props} onClick={() => this.file.click()}>
<input
ref={el => this.file = $(el)}
type="file"
accept={accept}
style={{display: 'none'}}
onChange={onChange}
/>
{children}
</Button>;
}
}
export default FileButton;
We came to the conclusion that reusable components must be of two kinds:
dumb components, i.e. components that only receive props and trigger "actions" via props callbacks only. These components have minimal internal state or at all. These are the most frequent of reusable components, and your file selector will probably fall in that case. A styled Text Input or custom List would be good examples too.
connected components that provide their own actions and reducer. These components have their own life within the application and are rather independent from the rest. A typical example would be a "top error message box" that displays on top of everything else when the application fails critically. In such a case the application triggers an "error action" with the appropriate message as payload and on the following re-render, the message box displays on top of the rest.

Where should I load data from server in Redux + ReactJS?

For example I have two components - ListOfGroupsPage and GroupPage.
In ListOfGroupsPage I load list of groups from the server and store it to the state.groups
In route I have mapping like ‘group/:id’ for GroupPage
When this address is loaded, the app shows GroupPage, and here I get the data for group from state.groups (try to find group in state via id).
All works fine.
But if I reload page, I'm still on page /group/2, so GroupPage is shown. But state is empty, so the app can't find the group.
What is the proper way to load data in React + Redux? I can see this ways:
1) Load all data in root component. It will be very big overhead from traffic side
2) Don't rely on store, try to load required data on each component. It's more safe way. But I don't think that load the same data for each component - it's cool idea. Then we don't need the state - because each component will fetch the data from server
3) ??? Probably add some kind of checking in each component - first try to find required data in store. If can't - load from the server. But it requires much of logic in each component.
So, is there the best solution to fetch data from server in case of usage Redux + ReactJS?
One approach to this is to use redux-thunk to check if the data exist in the redux store and if not, send a server request to load the missing info.
Your GroupPage component will look something like
class GroupPage extends Component {
componentWillMount() {
const groupId = this.props.params.groupId
this.props.loadGroupPage(groupId);
}
...
}
And in your action...
const loadGroupPage = (groupId) => (dispatch, getState) => {
// check if data is in redux store
// assuming your state.groups is object with ids as property
const {
groups: {
[groupId]: groupPageData = false
}
} = getState();
if (!groupPageData) {
//fetch data from the server
dispatch(...)
}
}
I recommend caching the information on the client using localstorage. Persist your Redux state, or important parts of it, to localstorage on state change, and check for existing records in localstorage on load. Since the data would be on the client, it would be simple and quick to retrieve.
The way I approach this is to fetch from the server straight after the store has been created. I do this by dispatching actions. I also use thunks to set isFetching = true upon a *_REQUEST and set that back to false after a *_SUCCESS or *_FAILURE. This allows me to display the user things like a progress bar or spinner. I think you're probably overestimating the 'traffic' issue because it will be executed asynchronosly as long as you structure your components in a way that won't break if that particular part of the store is empty.
The issue you're seeing of "can't get groups of undefined" (you mentioned in a comment) is probably because you've got an object and are doing .groups on it. That object is most likely empty because it hasn't been populated. There are couple of things to consider here:
Using ternary operators in your components to check that someObject.groups isn't null; or
Detailing in the initialState for someObject.groups to be an empty array. That way if you were to do .map it would not error.
Use selectors to retrieve the list of groups and if someObject.groups is null return an empty array.
You can see an example of how I did this in a small test app. Have a look at specifically:
/src/index.js for the initial dispatch
/src/redux/modules/characters.js for the use of thunks
/src/redux/selectors/characters.js for the population of the comics, series, etc. which are used in the CharacterDetails component

React Redux: More containers v.s. less containers

As I get further into implementing redux + react into a fairly complex app which depends on many API requests to load a single page, I'm having trouble deciding whether it's better to have a single container component at the root of the page which handles all async stuff and passes props down to dumb components, v.s. having multiple container components which concern themselves only with the data they need, as well as fetching the data they need. I've gone back and forth between these two patterns and found that they each have pros/cons:
If I put a single container component at the top:
pro: All isFetching props and fetchSomeDependency() actions can be handled in one place.
con: the downside which is really annoying is that I find myself having to forward props and callbacks through multiple components, and certain components in the middle of the tree end up being tied up to this.
Here's a visual example of the issue that shows the relationships required props-wise:
<MyContainer
data={this.props.data}
isFetchingData={this.props.isFetchingData}
fetchData={this.props.fetchData}
>
{!isFetchingData &&
<MyModal
someData={props.data}
fetchData={props.fetchData}
>
<MyModalContent
someData={props.data}
fetchData={props.fetchData}
>
<SomethingThatDependsOnData someData={props.someData} />
<SomeButtonThatFetchesData onClick={props.fetchData} />
</MyModalContent>
</MyModal>
}
</MyContainer>
As you can see, <MyModal /> and <MyModalContent /> now need to be concerned with props that have nothing to do with it, seeing as a modal should be able to be re-used and only be concerned with stylistic qualities of a modal.
At first the above seemed great but once I got to 100+ components it all felt very tangled, and I found the complexity of these top-level container components to be too high for my liking, seeing as most of them (in the app I'm working on) depend on responses from 3+ API requests.
Then I decided to try multiple containers:
pro: Completely removes the need to forward props. It still makes sense to do it in some cases, but it's a lot more flexible.
pro: Way easier to refactor. I'm surprised at how I can significantly move around and refactor components without anything breaking, whereas in the other pattern things broke a lot.
pro: The complexity of each container component is much less. My mapStateToProps and mapDispatchToProps is more specific to the purpose of the component it's in.
con: Any component that depends on async stuff will always need to handle isFetching state in itself. This adds complexity that is not necessary in the pattern where its handled in a single container component.
So the main dilemma is that if I use one container, I get this un-necessary complexity in components between the root container and the leaf components. If I use multiple containers, I get more complexity in the leaf components, and end up with buttons that need to worry about isFetching even though a button should not be concerned about that.
I'd like to know if anyone has found a way to avoid both cons, and if so, what is the "rule of thumb" you follow to avoid this?
Thanks!
The way I have always seen it is to have your containers at the top most component of a logical components group other than your root/app component.
So if we have a simple search app that display results and lets assume the component heiarchy is such
<Root> <- setup the app
<App>
<Search/> <- search input
<Results/> <- results table
</App>
</Root>
I would make Search and Results redux aware containers. Because react component are suppose to be composable. You might have other components or pages that need display Results or Search. If you delegate the data fetch and store awareness to the root or app component, it make the components become dependent on each other/app. This make it harder down the line when you have to implement changes, now you have to change all the places that use them.
The exception to this is probably if you do have really tightly coupled logic between components. Even then, I would say then you should create a container that wraps your tightly coupled components since they won't be abled to be used realistically without each other.
Redux author Dan Abramov suggests that you use container components when you need them. That is, once you get to have too many props wiring up and down between components it's time to use containers.
He calls it an "ongoing process of refactoring".
See this article: https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
I wouldn't even consider using a single container approach. It pretty much entirely negates all advantages of redux. There is no need whatsoever to have a state management system if all your state is in one place and all your callbacks are in one place (root component).
I think there's a thin line to walk, though. I'm making an app where I've been at it for about 5 weeks (part time) and it's up to 3000 lines right now. It has 3 levels of view nesting, a routing mechanism i implemented myself, and components that are 10+ levels of nesting deep that need to modify state. I basically have one redux container for each big screen and it works marvelously.
However, if I click on my "clients" view, I get a clients listing which is fine, since my clients view is inside a redux container and gets the list of clients passed as props. However, when I click on one client, I'm really hesitant to do another redux container for the individual client's profile since it's only one additional level of passing props. It seems that depending on the scope of the app, you might want to pass props up to 1-2 levels past the redux container and if it's any more than that, then just create another redux container. Then again, if it's an even more complex app, then the mixing of sometimes using redux containers and some other times not using them could be even worse for maintainability. In short, my opinion is trying to minimize redux containers wherever possible but definitely not at the expense of complex prop chains, since that's the main point of using redux to begin with.
So it's been over 2 years since I've posted this question, and this whole time
I have been consistently working with React/Redux. My general rule of thumb now
is the following: Use more containers, but try to write components in such a way where they don't need to know about isFetching.
For example, here is a typical example of how I would have built a to-do list before:
function Todos({ isFetching, items }) {
if (isFetching) return <div>Loading...</div>
return (
<ul>
{items.map(item =>
<li key={item.id}>...</li>
)}
</ul>
)
}
Now I would do something more like:
function Todos({ items }) {
if (!items.length) return <div>No items!</div>
return (
<ul>
{items.map(item =>
<li key={item.id}>...</li>
)}
</ul>
)
}
This way, you only have to connect the data, and the component has no concerns about states of asynchronous API calls.
Most things can be written this way. I rarely need isFetching, but when I do it is typically because:
I need to prevent, for example, a submit button from being clicked a second time, which makes an API call, in which case the prop should probably be called disableSubmit rather than isFetching, or
I want to explicitly show a loader when something is waiting for an asynchronous response.
Now, you might think, "wouldn't you want to show a loader when items are being fetched in the above todos example?" but in practice, actually I wouldn't.
The reason for this is that in the above example, let's say you were polling for new todos, or when you add a todo, you "refetch" the todos. What would happen in the first example is that every time this happened, the todos would disappear and get replaced with "Loading..." frequently.
However, in the second example that is not concerned with isFetching, the new items are simply appended/removed. This is much better UX in my opinion.
In fact, before posting this, I went through all the UI code for an exchange interface I wrote which is quite complex and did not find a single instance of having to connect isFetching to a container component that I wrote.
You don't have to dispatch AND load your state in the same place.
In other words, your button can dispatch the async request, while another component can check if you're loading.
So for example:
// < SomeButtonThatFetchesData.js>
const mapDispatchToProps = (dispatch) => ({
onLoad: (payload) =>
dispatch({ type: DATA_LOADED, payload })
});
You'll need to have some middleware to handle a loading state. It needs to update isFetching when you're passing an async payload.
For example:
const promiseMiddleware = store => next => action => {
if (isPromise(action.payload)) {
store.dispatch({ type: ASYNC_START, subtype: action.type });
Then you can use it wherever you want:
// <MyContainer.js>
const mapStateToProps = (state) => ({
isFetching: state.isFetching
});
And load the data in your inner nested component:
// <SomethingThatDependsOnData.js>
const mapStateToProps = (state) => ({
someData: state.someData
});

Resources