multiple dispatches with callback in react-hook?

Viewed 2849

how to add loading state to true in 'addItem' (reducer case), and set the loading state to false?

But I'm stuck using react-hook https://codesandbox.io/s/new-water-vczdp

I did it here: https://codesandbox.io/s/react-todolist-3dko3 with older react version.

What to do here?

case "addItem": {
      //fakeHttp();

      const { toAddItem, items } = state;
      const nextId = +items[items.length - 1].id + 1;

      return {
        items: [...items, { id: nextId, name: toAddItem }],
        loading: false
      };
    }
1 Answers

You don't have to call async functions in your reducer. You have to use other hooks for this. In your case, you should use useCallback hook:

function App() {
  const [{ items, toAddItem, loading }, dispatch] = useReducer(
    reducer,
    initialState
  );

  const addItem = useCallback(() => {
    async function fakeHttp() {
      dispatch({ type: "loading" });
      await delay(500);
      dispatch({ type: "addItem"})
    }
    fakeHttp();
  }, []);

  return (
    ...
    <AddList
        handleInput={e =>
          dispatch({ type: "handleInput", value: e.target.value })
        }
        toAddItem={toAddItem}
        addItem={addItem}
        loading={loading}
      />
  )
}

I make some changes in your sandbox example. You could see a working example here: https://codesandbox.io/embed/stupefied-currying-l39il

Related