My database stores a list of items. I've written a query to randomly return one item from the list each time a button is clicked. I use useLazyQuery and call the returned function to execute the query and it works fine. I can call the refetch function on subsequent button presses and it returns another random item correctly.
The problem comes when i try to pass variables to the query. I want to provide different criteria to the query to tailor how the random choice is made. Whatever variables I pass to the first call are repeated on each refetch, even though they have changed. I can trace that they are different on the client but the resolver traces the previous variables.
// My query
const PICK = gql`
query Pick($options: PickOptionsInput) {
pick(options: $options) {
title
}
}
`;
// My lazy hook
const [pick, { data, refetch }] = useLazyQuery(PICK, {
fetchPolicy: "no-cache",
});
// My button
<MyButton
onPick={(options) =>
(refetch || pick)({ // Refetch unless this is the first click, then pick
variables: {
options // Options is a custom object of data used to control the pick
},
})
}
/>
Some things I've tried:
Various cache policies
Not using an object for the options and defining each possible option as a different variable
I'm really stumped. It seems like the docs say new variables are supposed to be used if they are provided on refetch. I don't think the cache policy is relevant...I'm getting fresh results on each call, it's just the input variables that are stale.
I guess only pick is called ...
... because for <MyBytton/> there is no props change, no onPick redefined - always the first handler definition used (from first render) and options state from the same time ...
Try to pass all (options, pick and refetch) as direct props to force rerendering and handler redefinition:
<MyButton
options={options}
pick={pick}
refetch={refetch}
onPick={(options) =>
(refetch || pick)({ // Refetch unless this is the first click, then pick
variables: {
options // Options is a custom object of data used to control the pick
},
})
}
/>
... or [better] define handler before passing it into <MyButton/>:
const pickHandler = useCallback(
(options) => {
if(refetch) {
console.log('refetch', options);
refetch( { variables: { options }});
} else {
console.log('pick', options);
pick( { variables: { options }});
}
},
[options, pick, refetch]
);
<MyButton onPick={pickHandler} />
Related
I got multiple buttons that render different modals.
The modals may render different results according to the data provided in the state.
I got 3 state brackets I need to consider
const [cartChangeStoreShow, setCartChangeStoreShow] = useState(false);
const [orderLineId, setOrderLineId] = useState('');
const [storeId, setStoreId] = useState('');
cartChangeStoreShow is for controlling the visible state of the modal
What I want to do is I wanna change OrderLineId and storeId before rendering the component.
The data will change according to the orderlineId and storeId.
The component is like this
<CartChangeStorePopUp
visibility={cartChangeStoreShow}
setCartChangeStoreShow={setCartChangeStoreShow}
orderLineId={orderLineId}
storeId={storeId}
/>
I am calling api inside CartChangeStorePopUp component according to prop data.
So I am handing the user press button like this.
<TouchableOpacity
onPress={() => renderCartChangeStore(cartItem)}>
<Text>
Change Store
</Text>
</TouchableOpacity>
const renderCartChangeStore = async cartItem => {
try {
await setOrderLineId(cartItem.orderLineId);
await setStoreId(cartItem.storeId);
} catch (err) {
console.log(err);
} finally {
setCartChangeStoreShow(true);
}
};
the code is working now but from what I read before
Async Await doesn't work properly with setState,So I wanna know if there is potential error with the code written here
To me, it does not make sense both the async/await presence and the try/catch/finally.
Async/await is useful when the function you're calling is dealing with something like I/O, time-consuming, where you cannot do anything than "wait" for the completion. Since "to wait" might be something not desirable in a UI context, the async/await pattern helps you to keep track to the "slow function", but even leave the CPU free to serve other useful tasks.
That being said, the "setXXX" functions of React.useState are not time-consuming: no I/O or similar task involves. Hence, the async/await is not applicable.
Going further, the "setXXX" functions of React.useState throw no error on setting. They're much like setting a variable like so:
var storeId = "";
function setStoreId(value) {
storeId = value;
}
That is, the try/catch/finally is quite useless.
If you want, you might optimize the code by grouping the three variables as a single immutable object. However, that's up to your real code.
const [storeState, setStoreState] = useState({
cartChangeStoreShow: false,
storeId: "",
orderLineId: ""
});
const renderCartChangeStore = cartItem => {
setStoreState({
cartChangeStoreShow: true,
storeId: cartItem.storeId,
orderLineId: cartItem.orderLineId,
});
};
Here is a more compact way to achieve the same behavior:
const renderCartChangeStore = cartItem => {
setStoreState({
cartChangeStoreShow: true,
...cartItem,
});
};
Bear in mind that is very important that you treat the storeState as immutable. That is, never ever change a field of the object, rather create a brand new object with the new field value.
At that point, the component should be called like so:
const handleCartChangeStoreShow = value => {
setStoreState({
...storeState,
cartChangeStoreShow: value,
});
}
<CartChangeStorePopUp
visibility={storeState.cartChangeStoreShow}
setCartChangeStoreShow={handleCartChangeStoreShow}
orderLineId={storeState.orderLineId}
storeId={storeState.storeId}
/>
Notice the handler to correctly alter the storeState object. Worthwhile mention how the new value is set. First, all the current storeState is copied to a fresh new object, then the new show value is also copied on the same object. However, since that happens after, it'll have an override-effect.
So i have a const with an array of objects, named "data", a state that receive that data so I can update the screen when I change it, and I have a function that filter that data.
Every time that the user change the state of an HTML select, I trigger a function named handleChange that calls the filter function, so the user user can see the filtered content.
The problem is that I want to reset the state that receives the data, with the original data before filtering it, so if the user change one of the selects, it filter based on the original data, not the previous changed one, but when I try to update the state with the const data value, it doesn't work.
Here is my code
const [list, setList] = useState<IData[]>([...data]);
const [filter, setFilter] = useState<IFilter>({
name: "",
color: "",
date: "",
});
function handleChange(
key: keyof IData,
event: React.ChangeEvent<{ value: string }>
): void {
const newFilter = { ...filter };
newFilter[key as keyof IData] = event.target.value;
setList([...data]); // reset the data
setFilter({ ...newFilter }); // set the filter value
filterList();
}
function filterList(): void {
const keys = Object.keys(filter) as Array<keyof IData>;
keys.forEach((key: keyof IData) => {
if (filter[key]) {
const newList = list.filter((item: IData) => item[key] === filter[key]);
setList([...newList]);
}
});
}
the problem is here
setList([...data]); // reset the data
setFilter({ ...newFilter }); // set the filter value
filterList();
apparently, when the filterList happens, the list state is not yet restarted with the data value, since if I console log it inside filterList(), it return me only the list that was previous filtered. Is there a way for me to make sure that the setList happens before filtering, so I'm sure that the list that is filtered is always based on the initial value?
You can access the updated values inside useEffect (more about useEffect), so instead of calling filterList() directly inside the handler you move it inside the hook:
React.useEffect(()=>{filterList();},[list,filter])
Alternatively, you can pass the values as parameters to the function, after you updated the state with them
filterList(newList, newFilter)
UPDATE
As you update list inside filterList you'll need some sort of a flag to indicate if you need to filter of not (I'd use useRef). Note that it would be preferable to pass parameters into filterList instead, because this way there will be one less rendering cycle. Here is a simplified example of how both can work, let me know if they make sense : https://jsfiddle.net/6xoeqkr3/
I want to randomize movies from theMovieDB API. First I send a request to access the ID of the latest entry:
const { loading: loadingLatest, error: errorLatest, data: latestData, refetch: refetchLatest } = useQuery(
LATEST_MOVIE_QUERY
);
Then I want to fetch data from a randomly selected ID between 1 and the number of the latest id. Using a variable dependant on the first query seems to break the app, so for now I'm just using the same movie every time upon mounting the component:
const [
movieState,
setMovieState
] = useState(120);
const { loading, error, data, refetch } = useQuery(ONE_MOVIE_BY_ID_QUERY, {
variables : { movieId: movieState },
skip : !latestData
});
I want to press a button to fetch a new random movie, but the problem is that many of the IDs in the API lead to deleted entries and then I get an error back. I want to keep refetching until I get a good response back but I have no idea to implement it. Right now my randomize function just looks like this:
const randomizeClick = () => {
let mostRecentID = latestData.latestMovie.id;
setMovieState(Math.floor(Math.random() * mostRecentID));
};
I'd be grateful if someone can help me how to implement this.
I think what you needs is the "useLazyQuery" functionality of Apollo. You can find more information about it here: https://www.apollographql.com/docs/react/data/queries/#executing-queries-manually
With useLazyQuery you can change your variables easily and this is meant to be fired after a certain event (click or something similar). The useQuery functionality will be loaded when the component is mounted.
In my NextJS application interfaced with a MongoDB API back-end - managed via GraphQL, I'm trying to implement the Apollo fetchMore feature, in order to update a component responsible to load more items from a data collection.
On page rendering, the component itself shows a "gallery" of 10 elements as its native functionality, populated via a GraphQL starting query. Then, I included a "load more" button to trigger the fetchMore function. The UX expects that if the user clicks the proper button, more 10 elements will going to be loaded in addition of the previous 10 - basically a classical async-infinite loading example.
By inspecting the app, I notice that both the queries are being returned successfully - the initialization one and the "load more 10 items" too managed by fetchMore - but the latter, after its execution, triggers the component's update that it's being re-initialized with the starter query instead of the fetchMore one.
To clarify it: on "load more" click, instead to see the next 10 gallery elements loaded - so to finally display a total of 20 - the component refreshes and displays the starter 10 elements, like its starting initialization - totally ignoring the fetchMore action, even if this one is being called, executed and received back with a populated 200 response.
Because this is my very first time in using it, I don't know if I'm missing something in my implementation, or I need to fix something. Anyway, here it goes:
Due to various reasons, I'm running the query in a parent component, then I pass the data as props to a child one:
Parent
// Initialization, etc.
[...]
const {loading: loadingIndex, error: errorIndex, data: dataIndex, fetchMore: fetchMoreIndex} = useQuery(ARTICLE_QUERY.articles.indexArticles, {
// Last 30 days
variables: {
live: live,
limit: 10
}
});
// Exception check
if (errorIndex) {
return <ErrorDb error={errorIndex} />
}
// DB fetching check
if (loadingIndex) {
return (
<section className="index-articles">
<h6>Index - Articles</h6>
<aside className="articles__loading">
<h6>Loading</h6>
</aside>
</section>
);
}
const articles = dataIndex.queryArticleContents;
return (
<IndexArticles labels={props.labels} articles={articles} fetchMore={fetchMoreIndex} />
);
Child
// Initialization, etc.
[...]
let limit = 10; // My query hypothetically limiter
const IndexArticles = (props) => {
useEffect(() => {
// This is a getter method responsible to manage the ```fetchMore``` response
getArticles(props.articles, props.fetchMore);
});
return (
<>
// Component sections
[...]
// Load button
{props.fetchMore &&
<button className="articles__load" title={props.labels.index.title} tabIndex={40}>{props.labels.index.cta}</button>
}
</>
);
function getArticles(articles, fetchMore) {
// Yes, I'm using jQuery with React. Just ignore it
$('.articles__load').on('click tap', function(e) {
e.preventDefault();
$(this).addClass('hidden');
$('.articles__loading').removeClass('hidden');
fetchMore({
variables: {
// Cursor is being pointed to the last available element of the current collection
lastLoaded: articles.length,
limit: limit += 10
},
updateQuery: (prev, {fetchMoreResult, ...rest}) => {
$('.articles__loading').addClass('hidden');
$(this).removeClass('hidden');
if (!fetchMoreResult) {
return prev;
}
return {
...fetchMoreResult,
queryArticleContents: [
...prev.queryArticleContents,
...fetchMoreResult.queryArticleContents
]
}
}
});
});
}
Anyone have experience with it or had experienced this case before?
Thanks in advance for the help
As suggested on the official community, my configuration was missing about the notifyOnNetworkStatusChange: true in the query options, which is responsible to update the component and append the new data.
By changing the code in this way:
Parent
const {
loading: loadingIndex,
error: errorIndex,
data: dataIndex,
// Add networkStatus property too in order to use notifyOnNetworkStatusChange properly
networkStatus: networkStatusIndex
fetchMore: fetchMoreIndex} = useQuery(ARTICLE_QUERY.articles.indexArticles, {
// Last 30 days
variables: {
live: live,
limit: 10
},
// Important for component refreshing with new data
notifyOnNetworkStatusChange: true
});
The problem has been solved.
Using useLazyQuery() hooks from #apollo/react-hooks I was able to execute a query on click of a button. But I cannot use it execute same query on consecutive clicks.
export default ({ queryVariables }) => {
const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, {
variables: queryVariables
});
return <div onClick={sendQuery}>Click here</div>;
}
In the above the sendQuery executes only once.
useLazyQuery uses the default network policy that of cache-first So I supposed your onClick function actually executes but because the returned value is what was in the cache, React notices no change in data as such the state is not updated since the returned data is what it already has that way no re-render and thing seem not to have changed. I suggest you should pass in a different network policy something like
const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, {
variables: queryVariables,
fetchPolicy: "network-only"
});
This will mean you want the most recent information from your api hence basically no caching.
You might also want to experiment on other option and see which one best suits you
like cache-and-network: you can find out a little more here understanding-apollo-fetch-policies
As per the docs, useLazyQuery accepts the parameter fetchPolicy.
const [lazyQuery, { data, loading }] = useLazyQuery(QUERY, {
fetchPolicy: 'no-cache'
});
With fetchPolicy set to no-cache, the query's result is not stored in the cache.