Получать новую страницу, когда пользователь нажимает кнопку с помощью Svelte и Sapper - PullRequest
0 голосов
/ 28 мая 2020

Я застрял в той части, которая извлекает больше данных, когда пользователь нажимает кнопку внизу страницы с помощью Svelte и Sapper.

Вот код.

 <script context="module">
  export function preload(page) {
    return this.fetch(`https://reqres.in/api/users?page=${$count}`) // I know this is not goint to work. but when the button is clicked, I want to fetch page 2 and merge it with page 1 data, show data in ascending order(page1, page2)
    .then(res1 => {
      return res1.json()
    }).then(res2 => {
      return { 
        currentPage: res2.page,
        per_page: res2.per_page,
        notices: res2.data,
        total: res2.total,
        totalPage: res2.total_pages
      }
    })
  }
</script>

<script>
  import { count } from '../../store.js'; // export const count = writable(1); from store.js file
  export let currentPage; // 1
  export let per_page; // 6
  export let notices; 
  export let total; // 12
  export let totalPage; // 2

  const handleClick= () => {
    if ($count < totalPage) {
      count.update(n => n + 1); // update count 1 to 2 and want to deliver changed value to fetch new page
    }
  }
</script>

<main>
  <div id="container">
    <h1 class="cont-tit">Notice Board</h1>

    <div class="noti-list-wrap">
    {#each notices as notice, i}
      <ul class="noti-list">
        <li>
          <a rel=prefetch href={`notice/${notice.id}`}>
            <p class="tit">{`${notice.first_name} ${notice.last_name}`}</p>
            <hr />
            <p class="date">
              {`notice no.${i}`}
            </p>
          </a>
        </li>
      </ul>
    {/each}
      <div class="show-more" on:click={handleClick}>show me more</div>
    </div>
  </div>
</main>

Сначала Я думал, что могу использовать $ count для получения данных страницы 2, но хранилище счетчиков импорта внутри script context = "module" не будет работать.

Есть ли способ доставить измененное значение хранилища для функции предварительной нагрузки?

Ответы [ 2 ]

1 голос
/ 29 мая 2020

Не пытайтесь загрузить дополнительные данные внутрь preload. Вместо этого относитесь к ним как к исходным данным - а они и есть - и добавляйте к ним обычным способом. чем 1 - чтобы дать общее представление о том, что я имею в виду:

<script context="module">
  export async function preload(page) {
    const res = await this.fetch('https://reqres.in/api/users?page=1');
    const data = await res.json();

    return { 
      currentPage: data.page,
      per_page: data.per_page,
      notices: data.data,
      total: data.total,
      totalPage: data.total_pages
    };
  }
</script>

<script>
  export let currentPage;
  export let per_page;
  export let notices;
  export let total;
  export let totalPage;

  const load_more = async () => {
    currentPage += 1;
    const res = await fetch('https://reqres.in/api/users?page=' + currentPage);
    const data = await res.json();

    notices = notices.concat(data.data);
  };
</script>

<!-- other stuff -->
{#if currentPage < totalPage}
  <button on:click={load_more}>show me more</button>
{/if}
0 голосов
/ 28 мая 2020

Я обычно использую ярлык также для обновления значения хранилища, например:

const handleClick= () => {
    if ($count < totalPage) {
      $count = $count + 1); // update count 1 to 2 and want to deliver changed value to fetch new page
    }
  }

Я не вижу кода, в котором вы фактически получаете базу n-й страницы на count.

...