У меня есть запрос, который использует initialdata , заполненный бэкэнд в документе на загрузке страницы. Таким образом, нет состояния загрузки, когда страница загружается. Тем не менее, мне также необходимо иметь возможность поместить этот запрос в состояние жесткой загрузки, где он не имеет данных и возвращается к состоянию Isloading. Однако, как только запрос будет возвращен в состояние жесткой загрузки, initialdata больше не следует использовать, поэтому Resetqueries не работает. < /P>
useUser< /code> должно сделать: < /p>
На странице загрузку, используйте initialdata. Не обновите фон, потому что данные, как известно, действительны. PrettyPrint-Override ">function useUser() {
// Preloaded data from the backend so we can immediately display the user on
// page load.
const userJson = JSON.parse(document.getElementById('user')?.textContent || 'null');
return useQuery({
queryKey: ['profile'],
queryFn: async () => {
const response = await fetch('/api/accounts/me/');
return await response.json();
},
// initial data is fresh, no need to refresh immediately.
initialData,
// do background refreshes that don't trigger a hard loading state
staleTime: 1000 * 60,
});
}
// This is used somewhere far away from useUser, so there's no way to check the
// loading status of resetUserMutation in the components that use useUser.
function resetUserMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
await fetch('...');
// Here, put useUser into hard loading state, not a background refresh.
// The cached data in useUser is now totally invalid and should never be
// used again. initialData should never be used again.
queryClient.hypotheticalHardReload({ queryKey: ['profile'] });
},
});
}
function SomeComponent() {
// useUser is used all over the code. resetUserMutation is not used here.
const userQ = useUser();
if (userQ is in hard loading state) {
// we can't display anything but a loading indicator in this state
return ;
} else {
// we can display stuff during regular background refreshes
return {userQ.data.username};
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ing-states
Usequery с инициатором и мягкими и жесткими состояниями нагрузки ⇐ Javascript
Форум по Javascript
-
Anonymous
1746205987
Anonymous
У меня есть запрос, который использует initialdata , заполненный бэкэнд в документе на загрузке страницы. Таким образом, нет состояния загрузки, когда страница загружается. Тем не менее, мне также необходимо иметь возможность поместить этот запрос в состояние жесткой загрузки, где он не имеет данных и возвращается к состоянию Isloading. Однако, как только запрос будет возвращен в состояние жесткой загрузки, initialdata больше не следует использовать, поэтому Resetqueries не работает. < /P>
useUser< /code> должно сделать: < /p>
На странице загрузку, используйте initialdata. Не обновите фон, потому что данные, как известно, действительны. PrettyPrint-Override ">function useUser() {
// Preloaded data from the backend so we can immediately display the user on
// page load.
const userJson = JSON.parse(document.getElementById('user')?.textContent || 'null');
return useQuery({
queryKey: ['profile'],
queryFn: async () => {
const response = await fetch('/api/accounts/me/');
return await response.json();
},
// initial data is fresh, no need to refresh immediately.
initialData,
// do background refreshes that don't trigger a hard loading state
staleTime: 1000 * 60,
});
}
// This is used somewhere far away from useUser, so there's no way to check the
// loading status of resetUserMutation in the components that use useUser.
function resetUserMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
await fetch('...');
// Here, put useUser into hard loading state, not a background refresh.
// The cached data in useUser is now totally invalid and should never be
// used again. initialData should never be used again.
queryClient.hypotheticalHardReload({ queryKey: ['profile'] });
},
});
}
function SomeComponent() {
// useUser is used all over the code. resetUserMutation is not used here.
const userQ = useUser();
if (userQ is in hard loading state) {
// we can't display anything but a loading indicator in this state
return ;
} else {
// we can display stuff during regular background refreshes
return {userQ.data.username};
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79603830/usequery-with-initialdata-and-soft-and-hard-loading-states[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия