3

The goal is to create a queue to store API requests.

Expected result:

  • every time the Add button is pressed, the request should be added to the queue;
  • once Sync button is pressed, all API requests from the queue should be fired and cleared

Here's what I've tried so far: https://codesandbox.io/s/elated-sky-e23w6?file=/src/App.js

There are a few problems here:

  • API calls are not fired;
  • _store gets cleared every time a new request is added;
  • sync is not working.
  • how can I store API request config?

How can this be solved? Thank you!

lecham
  • 2,294
  • 6
  • 22
  • 41

1 Answers1

0

The queue must be stored as state of a React component. What you need is the useState or useRef hook. The latter is better in your case because you already have implemented a BoxEventProcessor and you do not need to re-render any component when an add/submit button is clicked. (see the difference here)

const App = () => {
  const sendEventToServer = async (id) => { ... };

  const refBoxEventProcessor = React.useRef(
    createSerialProcessor(sendEventToServer)
  );

  const submit = (id) => {
    refBoxEventProcessor.current.addEvent(`param-${id}`, new Date().toString());
  };

  const onSync = () => {
    refBoxEventProcessor.current.processEvents();
  };

  return (<>...</>);

Above is a minimum example for useRef(). Its argument is an newly created instance of SerialProcessor, which will be stored in the object refBoxEventProcessor under the current property. It will be persistent upon latter re-rendering. All the user's "API requests" are stored in the queue of this object until the user click the sync button to clear the queue.

You might elaborate on the initialization (useRef) and submit functions to better fit your needs.

https://codesandbox.io/s/answer-to-so-70387163-0yqi5

gdlmx
  • 6,479
  • 1
  • 21
  • 39