Skip to content

[Question] How to do async actions the Pullstate Way™  #26

@Antonio-Laguna

Description

@Antonio-Laguna

Hi there!

I've been looking for some time for a decent alternative and less convoluted than Redux and I was ecstatic when I saw your module. Looks really nice!

I went through the docs and tried implementing it but felt a tad odd. I think my case is really straightforward and realized some people could run into this same pitfall or wonder so it could do for good examples that could enhance the docs/code.

Here's an "entity" which is a "page":

import { createAsyncAction, errorResult, successResult } from 'pullstate';
import ItemsStore from '../stores/items-store';

export function getPages() {
  return fetch(`${process.env.SERVER}/api/pages/pages?token=${process.env.TOKEN}`)
    .then(response => response.json())
    .then(json => json.map((name, index) => ({ index, name })));
}

export default createAsyncAction(
  async () => {
    const result = await getPages();

    if (result.length > 0) {
      return successResult(result);
    }

    return errorResult([], `Couldn't get pages: ${result.errorMessage}`);
  },
  {
    postActionHook: ({ result, stores }) => {
      if (!result.error) {
        ItemsStore.update(s => {
          s.pages = result.payload;
        });
      }
    },
    cacheBreakHook: ({ result, timeCached }) => {
      const CACHE_TIME = 60 * 60 * 1000; // 1 hour in milliseconds
      return timeCached + CACHE_TIME < Date.now();
    }
  },
);

Then on the view, I want to render this list of pages:

export function HomePage() {
  const [finished, result] = usePages.useBeckon();

  if (!finished) {
    return (
      <div>
        Loading...
      </div>
    );
  }

  if (result.error) {
    return <div>{result.message}</div>;
  }

  return (
    <div>
      <ul>
        {result.payload.map(page => (<li key={page.index}>{page}</li>))}
      </ul>
    </div>
  );
}

However, it feels a bit convoluted and the result.payload feels kind of dirty to me which is what got me thinking if we were doing it right.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationRelated to documenting the use of the libraryquestionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions