qwikqwikjs

how to prevent "routeLoader$" from executing 2 x when using "resolveValue"?


See this example causes my "routeLoader$" to be clled 2 times, which is an issue for obvious reasons? I couldnt understad how to prevent this.

Please help:

export const useNewsLoader = routeLoader$(async () => {
  return {
    data: 'example'
  };
})

export const head: DocumentHead = ({ resolveValue }) => {
  const newsData = resolveValue(useNewsLoader);
  ...
};

export default component$((props) => {
  const newsData = useNewsLoader();
  ...
});`

Solution

  • I looked into the Qwik source code and resolveValue is using the previous response. I also did this example to verify my thesis. In the console you can see the same random number.

    export const useNewsLoader = routeLoader$(async () => {
        // I also tested with a real endpoint and I saw one call
        // const res = await fetch('http://localhost:5173/api/test');
        const random = Math.random();
        console.log('1',random);
        return {test: random};
    });
    
    export const head: DocumentHead = ({ resolveValue }) => {
        const newsData = resolveValue(useNewsLoader);
        console.log('2',newsData.test );
        return {
            title: `${newsData.test}`,
            meta: [],
        };
    };
    
    export default component$(() => {
        const newsData = useNewsLoader();
        return <div></div>;
    });