Skip to content

Change deep state values directly using useAsyncDeepState hook

Dmitriy Mozgovoy edited this page Sep 21, 2021 · 1 revision

Using useAsyncDeepState hook you can mutate internal state values directly in the following way (Live Demo):

import React, { useEffect } from "react";
import { useAsyncDeepState } from "use-async-effect2";

function TestComponent() {
  const [state, setState] = useAsyncDeepState({
    items: []
  });

  useEffect(() => {
    console.log(`state has been changed (${JSON.stringify(state)})`);
  }, [state]);

  const addItem = async () => {
    state.items.push({
      name: "Mad Max",
      age: 35,
      added: Date.now()
    });
    setState(true); // we changed the state, so let's notify React about it
  };

  return (
    <div className="component">
      <div className="caption">useAsyncDeepState demo</div>
      <ul>
        {state.items.map((item, index) => (
          <li key={index}>{JSON.stringify(item, null, 2)}</li>
        ))}
      </ul>
      <button onClick={() => addItem()}>Add item</button>
    </div>
  );
}
Clone this wiki locally