Hey, When I have a component that has some kind of...
# react
h
Hey, When I have a component that has some kind of selector, a List with Elements for example, and a TanStackQuery with a QueryKey like
MY_FEATURE_<element_Id>
which changes based on the element clicked, via
useState
or
navigation
to a URL with the id in the path and via
params
. Now my problem, when I click on an entry it doesn't show the current one, it shows the content of the previous query key. If the query is set to update on focus or after 15s or so it corrects when it's refetched, but the inital result is always from the previous key. A snipped with some shortcuts to show what I mean,
Copy code
val PREVIEW_QUERY_KEY = "PREVIEW_QUERY_KEY"

val MyComponent = FC<Props> { props ->
    val navigate = useNavigate()
    val params = useParams()
    val selectedId = params["id"]?.toIntOrNull()
    val previewQuery = useQuery(queryKey = PREVIEW_QUERY_KEY + "_$selectedId") { /* fetch */ }
    
    val previewData = useMemo(selectedId, previewQuery.dataUpdatedAt) {
        previewQuery.data
    }
    
    List { // Display here lags behind one selection.
        data = previewData
        onClick = { event ->
            navigate(to = "/preview/${event.target.value}")
    }
}
I now did it like this and it seems to work, is this the correct way?
Copy code
val PREVIEW_QUERY_KEY = "PREVIEW_QUERY_KEY"

val MyComponent = FC<Props> { props ->
    val navigate = useNavigate()
    val params = useParams()
    val selectedId = params["id"]?.toIntOrNull()
    val (previewQueryKey, setPreviewQueryKey) = useState(PREVIEW_QUERY_KEY + "_$selectedId")
    val previewQuery = useQuery(queryKey = previewQueryKey) { /* fetch */ }
    
    val previewData = useMemo(previewQueryKey, previewQuery.dataUpdatedAt) {
        previewQuery.data
    }

    useEffect(selectedId) {
        setPreviewQueryKey(PREVIEW_QUERY_KEY + "_$selectedId")
    }
    
    List { // Display here lags behind one selection.
        data = previewData
        onClick = { event ->
            navigate(to = "/preview/${event.target.value}")
    }
}