0

React Query not updating my list on first render

My list is not updating when i come back after updating my list , but my api is returning updated data

export default function App() {
const [id] = useQueryState("category-id", parseAsInteger);

const queryKey = useMemo(() => ["list", id], [id]);

const { data: list,isLoading } = useQuery({
queryKey,
queryFn: () => getList({ categoryId: id || null }),
enabled: !!id,
refetchOnMount:'always',
staleTime:0
});

const isList1Empty = useMemo(() => {
    if (id !== 1 && !list) return false;

        return list.length === 0;
}, [id,list]);

const isList2Empty = useMemo(() => {
    if (id !== 2 && !list) return false;

                return list.length === 0;
}, [id,list]);

useEffect(() => {
if (!list) return;

    if (
        (id === 1 && isList1Empty) ||
        (id=== 2 &&  isList2Empty)
    ) {
    // navigate to update list page
    }
 }, [id,list]);


 if (isLoading) {
    return (
        <h1>loading</h1>
    );
 }



 return <div>{id === 1 ? <List1 list={list} /> : <List2 list={list}    />}</div>;
 }

Steps :

  1. Page loaded
  2. get list api called
  3. checks if list is empty
  4. if empty redirect to update form page
  5. updated my list
  6. comes back to this page
  7. getList returns updated list but its not updated on my ui listing on first mount
2
  • have you tried refetchOnMount: 'always' ? Commented May 21 at 8:49
  • already tried , did not work Commented May 21 at 9:32

1 Answer 1

0

I think the issue here is by the time your background refetch completes, your redirect logic has already executed.

Try adding refetchOnMount: 'always',

Also try using isFetching and isLoading properties in useQuery

const { data: list, isFetching, isLoading } = useQuery({
  queryKey,
  queryFn: () => getList({ categoryId: id || null }),
  enabled: !!id,
  staleTime: 0,
  refetchOnMount: 'always',
});

useEffect(() => {
  if(!isFetching && !isLoading && !list?.length){
    // navigate to list update form
  }
}, [list, isFetching, isLoading]);
Sign up to request clarification or add additional context in comments.

3 Comments

did not solve the issue
Could you share the code that updates the list and how you navigate back to this page?
if you console.log list outside of useEffect data is updated , but inside useEffect data is not updated, so it navigates to // navigate to update list page on mount

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.