reselect, Where do I put the calculate derive data logic? - reactjs

Recently, I start to learn reselect, and try to use it to my project.
But, I'm doubtful about where should I put the code that calculates the derived data.
Below is my code snippet, I think I put formatDate calcDayLeftFromNow setDeriveData logic to my reducer will also be fine.
I do the derive data calculate in my reducer will also be fine.
If I do this, it seems there is no reason to use reselect.
function formatDate(millisecond) {
let d = new Date(millisecond);
let dateArr = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
let date = dateArr.join('.');
return date;
}
function calcDayLeftFromNow(endTimeNum) {
const timeDiff = endTimeNum - new Date().getTime();
const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
return daysDiff;
}
function setDeriveData(coupons) {
return Object.values(coupons).map((coupon, index) => {
coupon.startDate = formatDate(coupon.startTimeNum);
coupon.endDate = formatDate(coupon.endTimeNum);
coupon.dayLeft = calcDayLeftFromNow(coupon.endTimeNum);
return coupon;
});
}
const mapStateToProps = state => {
const { coupons, current_tab, result, page } = state.yao_coupon;
const newCoupons = setDeriveData(coupons);
return {
coupons: newCoupons,
current_tab,
result,
page
};
};

It's common to put your selector's code in your container component. Or if you don't want to split container from presentational, just put it in your component.
Selectors' role is to compute derived data from the state (store).
Whereas reducers specify how the application's state changes in response to an action.
So they serve a very different role in your app.
In the Reselect readme, they're putting everything in one file just to showcase its use in the simplest way.
Here is a common folder structure that might help you make sense of this:
| reducers #folder
date.js
| components #folder
| Clock #folder
ClockContainer.js #contains mapStateToProps (and your selectors) and mapDispatchToProps
Clock.js #the clock component
Some people choose to put the selectors in a separate file. But it's up to you to decide. For example, you can put your selector in your container component and only move it to a separate file if it gets big. Another reason to move it to a separate file is in the event you need that same selector throughout parts of the app. (credits: #kwelch)
Edit
when I fetch bookList data from server, I calculate the derivedPrice in my FETCH_SUCCESS reducer
Calculating the derived price in your reducer will make it highly coupled with the api call, and you won't be able to use the dispatched action elsewhere.
My suggestion is to move this calculation out of the reducer and calculate the derivedPrice before dispatching the action.

Related

Should I create a context for something that is mostly useCallback or simply create a hook?

I'm just doing a bit of refactoring and I was wondering if I have a bunch of useCallback calls that I want to group together, is it better do it as a simple hook that I would reuse in a few places?
The result would be
interface IUtils {
something(req: Something) : Result;
somethingElse(req: SomethingElse) : Result;
// etc...
}
So a plain hooks example would be:
export function useUtils() : IUtils {
// there's more but basically for this example I am just using one.
// to narrow the focus down, the `use` methods on this
// block are mostly getting data from existing contexts
// and they themselves do not have any `useEffect`
const authenticatedClient = useAuthenticatedClient();
// this is a method that takes some of the common context stuff like client
// or userProfile etc from above and provides a simpler API for
// the hook users so they don't have to manually create those calls anymore
const something = useCallback((req:SomethingRequest)=> doSomething(authenticatedClient), [authenticatedClient]
// there are a few of the above too.
return {
something
}
}
The other option was to create a context similar to the above
const UtilsContext = createContext<IUtils>({ something: noop });
export UtilsProvider({children}:PropsWithChildren<{}>) : JSX.Element {
const authenticatedClient = useAuthenticatedClient();
const something = useCallback((req:SomethingRequest)=> doSomething(authenticatedClient), [authenticatedClient]
const contextValue = useMemo({something}, [something]);
return <UtilsContext.Provider value={contextValue}>{children}</UtilsContext.Provider>
}
The performance difference between the two approaches are not really visible (since I can only test it in the device) even on the debugger and I am not sure how to even set it up on set up on jsben.ch.
Having it as just a simple hook is easier I find because I don't have to deal with adding yet another component to the tree, but even if I use it in a number of places I don't see any visible improvement but the devices could be so fast that it's moot. But what's the best practice in this situation?

Recoil - single atom vs multiple atoms

I have an index file that contains a lot of atoms for a wizard I've created.
I thought about moving all the creations -
export const foo1State = atom<string>({
key: "foo1State",
default: "",
});
export const foo2State = atom<boolean>({
key: "foo2State",
default: false,
});
into one using JSON -
export const fooStates = atom<fooState>({
key: "fooStates",
default: {
foo1State: string = "",
foo2State: boolean = false,
}
});
Is that a better approach?
I'll mention that all that inputs are changing frequently so need to consider the renders.
What do you think?
Thanks
If you have separate atoms for each state, then you can independently subscribe to each one. If you combine them all into one, a component that renders foo1State will re-render every time you update foo2State and vice versa. This can be problematic if the atom gets really big.
If you don't have any particular reason why you would need to hold foo1State and foo2State in single atom, go with your first approach, and keep them in separate atoms.

RTK Query: Accessing cached data outside of a react component

We are in the process of integrating RTK query in our app.
Our current "architecture" is as follow:
All the business logic actions are written inside services which are plain JS classes.
Those services are passed using react context in order for the component tree to be able to call services functions.
As of now those services were accessing the redux store directly to perform the appropriate logic.
Now that we are moving to RTK, accessing the RTK cache from a service is less trivial:
As far as I can see, the only way to access it is via the select function of the relevant endpoint.
The point is that this method is a "selector factory" and using it outside of a react component doesn't seems to be the right way to go.
Here is an exemple:
class TodoService {
getTodoTitle( todoId: string ) {
// This doesn't looks the right way to do it
const todoSelector = api.endpoints.getTodo.select( {id: todoId } );
const todo = todoSelector( state )
return todo.data.title
}
}
Is there any way to implement safely the following code
class TodoService {
getTodoTitle( todoId: string ) {
// Is there any way to do that kind of call ?
const todoEntry = api.endpoints.getTodo.getCacheEntry( {id: todoId } );
return todoEntry.data.title
}
}
I guess that the answer is "no" and I have to refactor our whole architecture, but before doing so I'd like to be sure that there is no alternate approach.
Note that I could build the cache entry key by myself, but that also doesn't sound like a robust approach...
The thing is that you don't want to just get the cache entry - the selector does a little more for you than just that.
So let's just stay with "please use the selector" and "we won't add another way of doing that" because, selectors is how your code should interact with Redux all the time - React or not.
If you are not calling this code from React where you would need a stable object reference, it is good as it is. The selector factory will create a new selector and thus you get an un-memoized result. This is not perfect, but if you are not relying on referential equality, it also does not hurt at all.
If you want to have the referential equality, you'll have to store the selector in some way, probably as a class property.
Something like this would be possible:
class TodoService {
getSelectorForTodo(todoId: string) {
if (this._lastId !== todoId)
this._lastSelector = api.endpoints.getTodo.select( {id: todoId } )
return this._lastSelector
}
getTodoTitle( todoId: string ) {
const todo = this.getSelectorForTodo(todoId)(state)
return todo.data.title
}
}

Find element by id in react-testing-library

I'm using react-testing-libarary to test my react application. For some reason, I need to be able to find the element by id and not data-testid. There is no way to achieve this in the documentation.
Is there a way to achieve this?
I have the rendered output as follows:
const dom = render(<App />);
I'm looking for something along the lines of:
const input = dom.getElementById('firstinput');
//or
const input = dom.getById('firstinput');
I feel like none of the answers really gave a complete solution, so here it is:
const result = render(<SomeComponent />);
const someElement = result.container.querySelector('#some-id');
I found a way to do this.
import App from './App';
import { render, queryByAttribute } from 'react-testing-library';
const getById = queryByAttribute.bind(null, 'id');
const dom = render(<App />);
const table = getById(dom.container, 'directory-table');
I hope this helps.
It looks you have DOM node itself as a container. Therefore, you should be able to call .querySelector('#firstinput') with that.
There are two ways to do so
Simply use container.getElementById('id'). In the end, all the helpers are doing is making queries like this one under the hood
If you want to have your custom query you can write a custom render. Check the documentation for more info https://github.com/kentcdodds/react-testing-library#getbytestidtext-textmatch-htmlelement
As a final note, if you can avoid looking for elements by id it's better.
You can set up with testIdAttribute in the configuration.
configure({ testIdAttribute: 'id' })
https://testing-library.com/docs/dom-testing-library/api-configuration
The setting has pros and cons. The benefit of it is that you can set an id for multiple uses. (Test id, marketing analytics, tag manager, ...etc) You don't have to add both id and test-id. It's good for the conciseness of the code.
But be careful, you might accidentally set the same id at two different components on the same page. Remember to add index or identification to a component id for list items.
My advice: stop adding and searching by ids, this always takes to much time and effort because you have to add the ids (sometimes test-ids) and then find out the best way to query the element. But even if you really need an id, this tool will save you a lot of time by showing the best way to query any DOM element on your screen: Testing Playground
If you use TypeScript, and want to get a non-null result, here's a convenience function:
function getById<T extends Element>(container: HTMLElement, id: string): T {
const element = container.querySelector<T>(`#${id}`);
assert(element !== null, `Unable to find an element with ID #${id}.`)
return element;
}
You can then use it like this:
import { render } from '#testing-library/react';
const { container } = render(<App />);
const myInputElement = getById<HTMLInputElement>(container, 'myInputElement');

How to update variables using createRefetchContainer?

Since the React Relay createPaginationContainer does not support offset-based pagination, the next best option would be to handle this feature through the use of the createRefetchContainer.
In the example provided on the Relay Modern documentation https://facebook.github.io/relay/docs/refetch-container.html, when implemented will paginate forward one time, but only because we are transitioning from our default state at offset of 0 to our new state of 0 + 10. Subsequent click events produce the same result since the values are not being stored.
I would have expected that the offset value would continue to increment but it does not appear that the state is being maintained through each refetch.
I came across this issue on the repo which seems to have addressed this, https://github.com/facebook/relay/issues/1695. If this is the case then the documentation has not been updated.
While I believe there should be a built in mechanism for this, I ultimately ended up storing values in state and using callbacks to trigger my refetch.
So in the example above which I listed from the documentation the update appears to happen here:
_loadMore() {
// Increments the number of stories being rendered by 10.
const refetchVariables = fragmentVariables => ({
count: fragmentVariables.count + 10,
});
this.props.relay.refetch(refetchVariables, null);
}
So the issue I have with this particular example is that we are pulling the default state from the fragmentVariable so in essence no real change is ever occurring. This may be acceptable depending on your implementation but I feel that for most use cases we would like to see values being actually updated as variables in the updated fragment.
So the way I approached this in terms of my offset-based pagination was...
_nextPage = () => {
if ((this.state.offset + this.state.limit) < (this.state.total - this.state.limit) {
this.setState({ offset: (this.state.offset + this.state.limit), () => {
this._loadMore();
}
}
}
_loadMore = () => {
const refetchVariables = {
offset: this.state.offset,
limit: this.state.limit
}
this.props.relay.refetch(refetchVariables, null);
}
May have a typo, I'm not actually looking at my code right now. But by using the state of the component, you will effectively be able to update the variables of the refetchContainer.

Resources