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.
Related
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?
thanks in advance for your attention with this (I believe) very basic question. I'm working on building my first "full-stack" application, and am running into something I can't quite wrap my head around with React-Redux. A brief explanation of the project: users can submit band idea names, and up or down vote others' submissions. Now, I believe that my problem is I'm not interacting with the state appropriately in my reducer dealing with MODIFY_BAND_SCORE actions. Here's the git repository, and I'll also copy and paste my store reducers here:
export const store = createStore(
combineReducers({
bands(bands = defaultState.bands, action) {
switch (action.type) {
case mutations.CREATE_BAND:
return [
...bands,
{
id: action.id,
owner: action.owner,
name: action.name,
score: 0,
flags: 0,
},
];
case mutations.MODIFY_BAND_SCORE:
let targetBandIndex = bands.findIndex(
(band) => band.id === action.bandID
);
let targetBand = bands.splice(targetBandIndex, 1)[0];
targetBand.score = targetBand.score + action.value;
bands.splice(targetBandIndex, 0, targetBand);
return bands;
}
return bands;
},
users(users = defaultState.users, action) {
return users;
},
}),
applyMiddleware(createLogger(), sagaMiddleware)
);
Hopefully that's enough context to make informed suggestions about what's going on here—my apologies for not having a truly minimal working example for this! The behavior I'm seeing from Redux-Logger when I dispatch an action of type MODIFY_BAND_SCORE is that I am (in a way) seeing the change reflected in that the correct band is having its score modified by the correct amount, but it is showing somehow in the previous and next states! Here's a screenshot:
I feel like I've maybe made this post longer than what it needs to be, am I correct in thinking that in my case for mutations.MODIFY_BAND_SCORE I'm actually modifying the state directly? This is probably occurring with my calling of .splice() on bands isn't it?
Like Siddharth mentioned,
let copyOfBands = [...bands]
will create a copy for you. It's important to remember that one of the key parts of Redux is that the store is read-only. It can be easy to forget that when dealing with non-primitive data (I've certainly done that a bunch), but you should always try to remember to make copies of the data, modify the copy, and then push the copy to store. This helps prevent you from getting really weird and hard to debug errors.
It is important to remember that the spread operator here will creates a shallow copy of the array, which means if you have other non-primitive objects inside the array (such as other arrays), you will have to copy those as well.
I'm having a hard time figuring out how to update a list of items (in the cache). When a new item is created with react-apollo.
The <CreateItemButton /> component is (in my case) not nested within <ListItems /> component. From what I can figure out, I need to update the cache via the update function in my createItemButton <Mutation /> component.
The problem is when I try to store.readQuery({query: GET_LIST_ITEMS, variables: ???}) to get the current list of items (to append my recently created item), this can have variables/filters (for pagination, sorting etc.).
How do I know what variable to pass to the store.readQuery function, is there a sort of "last used variables" around this, or do you have any other suggestion on how to solve this issue?
This is a known Apollo issue and the team is working on it. The current options you have can be found in this medium post.
It is also an issue with deleting/updating an item when you have it in a list with filters or pagination.
Here is a reference of an opened issue on Github about it
This seems to work, but a bit hacky to access the cache.watches Set? :S
The trick is to access the cache's variables for a given query, save it and perform a refetch with the given query variables. In my case after creation of an item:
export const getGraphqlCacheVariables = (queryName, cache) => {
if (cache.watches) {
const watch = [...cache.watches].find(w => !!w.query[queryName]);
if (watch) {
return watch.variables;
}
}
};
The mutation update function:
let variables;
const update = (cache, { data }) => {
if (data && data.createTask && data.createTask.task) {
variables = getGraphqlCacheVariables('GetTasks', cache);
}
}
And the refetchQueries function:
const refetchQueries = () => {
if (variables && Object.keys(variables).length > 0) {
return [{ query: GET_TASKS, variables }];
}
return [];
}
Bot the update and refetchQueries functions should have access to the variables variable
The benefit compared to the solution in the Medium article, is that you're not deleting the cached data for a given query (GET_TASKS) with different variables.
Apollo now provides a new directive that allows ignoring of some variables when querying the cache. Check it here. I've used it to ignore my changing pagination params.
I'm trying to animate View with interpolate. I'd like to get a current value of my Animated.Value, but don't know how. I didn't understand how to do it with React-native docs.
this.state = {
translateAnim: new Animated.Value(0)
}
DeviceEventEmitter.addListener('Accelerometer', function (data) {
console.log(this.state.translateAnim);
// returns an object, but I need a value in current moment
}
I find out, how to get a value:
this.state.translateAnim.addListener(({value}) => this._value = value);
EDIT
to log a value I do the following:
console.log(this.state.translateAnim._value)
This also works for me...
const headerHeight = new Animated.Value(0);
After some manipulation....
console.log(headerHeight.__getValue())
It feels hackish but it gets the job done...
For the people with typescript.
console.log((this.state.translateAnim as any)._value);
It worked for me to full tsc as any.
Number.parseInt(JSON.stringify(translateAnim))
It works on React Hook
edit: CAUTION - MAY CAUSE SEVERE PERFORMANCE ISSUES. I have not been able to figure out why, but if you use this for 30+ simultaneous animations your framerate will slow to a crawl. It seems like it must be a bug in react-native with Animated.Value addListener as I don't see anything wrong with my code, it only sets a listener which sets a ref which should be instantaneous.
Here's a hook I came up with to do it without resorting to accessing private internal values.
/**
* Since there's no (official) way to read an Animated.Value synchronously this is the best solution I could come up with
* to have access to an up-to-date copy of the latest value without sacrificing performance.
*
* #param animatedValue the Animated.Value to track
* #param initial Optional initial value if you know it to initialize the latest value ref before the animated value listener fires for the first time
*
* returns a ref with the latest value of the Animated.Value and a boolean ref indicating if a value has been received yet
*/
const useAnimatedLatestValueRef = (animatedValue: Animated.Value, initial?: number) => {
//If we're given an initial value then we can pretend we've received a value from the listener already
const latestValueRef = useRef(initial ?? 0)
const initialized = useRef(typeof initial == "number")
useEffect(() => {
const id = animatedValue.addListener((v) => {
//Store the latest animated value
latestValueRef.current = v.value
//Indicate that we've recieved a value
initialized.current = true
})
//Return a deregister function to clean up
return () => animatedValue.removeListener(id)
//Note that the behavior here isn't 100% correct if the animatedValue changes -- the returned ref
//may refer to the previous animatedValue's latest value until the new listener returns a value
}, [animatedValue])
return [latestValueRef, initialized] as const
}
It seems like private property. But works for me. Helpful for debugging, but wouldn't recommend using it in production.
translateAnim._value
I actually found another way to get the value (not sure if it is a recommended way, but it works).
Use JSON.stringify() on the animated value and use Number on the result to convert it into Number.
E.g,
const animatedVal = new Animated.Value(0);
const jsanimated = JSON.stringify(animatedVal);
const finalResult = Number(jsanimated)
I've been working with react/flux for a few weeks now and while I feel like I've got a pretty good handle on everything from async loading to updating props/states/etc, one thing that is still bothering me is how to handle save states.
For example, when loading data, I just have an isLoading boolean parameter in my store that gets passed to my components. But when I try and post an updated object to the server, it's trivial to:
fire the update action
display a "save in progress" state
but figuring out the result of the update action seems to be way more difficult.
Probably the most applicable post I've seen on this is in Fluxxor's async data guide, but their solution (adding/modifying a status property on the object) feels error-prone to me.
onAddBuzz: function(payload) {
var word = {id: payload.id, word: payload.word, status: "ADDING"};
this.words[payload.id] = word;
this.emit("change");
},
onAddBuzzSuccess: function(payload) {
this.words[payload.id].status = "OK";
this.emit("change");
},
onAddBuzzFail: function(payload) {
this.words[payload.id].status = "ERROR";
this.words[payload.id].error = payload.error;
this.emit("change");
}
Is there a better way to manage save states or is adding a status property to the object the best way?
I recommend keeping your "model stores" and "ui stores" separate, or at least accessed via different cursor positions in the same store. So, in your case you'd have one store or branch for your "word model" and then another store or branch for "word status."
While this adds some complexity in the form of breaking up logic across stores and reacting twice to the AddBuzz action, it ends up reducing (more) complexity by confining model store updates to true changes in model data and managing ui states separately.
EDIT
This is what Relay will more-or-less be doing, keeping persisted data in a separate self-managed store, leaving custom stores for nothing but ui state. Some other libraries like https://github.com/Yomguithereal/baobab also recommend this approach. The idea is that these are fundamentally different kinds of state. One is domain-specific persisted data and the other is ui-specific ephemeral application state.
It might look something like this:
model_store.js:
onAddBuzz: function(payload) {
var word = {id: payload.id, word: payload.word};
this.words[payload.id] = word;
this.emit("change");
}
ui_store.js:
onAddBuzz: function(payload) {
this.wordStates[payload.id] = 'ADDING';
this.emit("change");
}
my_view_controller.js:
// listen to both stores and pass down both words and wordStates to your views
my_word_view.js:
...
render: function() {
var word = this.props.word,
wordState = this.props.wordState;
...
}
If you don't want to emit two change events, have one waitFor the other and emit the change only from the second one.