UNPKG

react-hook-deep-state

Version:

![NPM Version](https://img.shields.io/npm/v/react-hook-deep-state) ![NPM Last Update](https://img.shields.io/npm/last-update/react-hook-deep-state) ![NPM Type Definitions](https://img.shields.io/npm/types/react-hook-deep-state) ![NPM Downloads](https://im

46 lines (45 loc) 1.07 kB
import { useState as g } from "react"; function o(r) { return r !== null && typeof r == "object" && !Array.isArray(r); } function y(r, i) { const n = { ...r }; for (const u of Object.keys(i)) { const t = i[u]; if (o(t)) { const f = n[u]; o(f) ? n[u] = y(f, t) : n[u] = y({}, t); } else n[u] = t; } return n; } function w(r) { const [i, n] = g(r); return [i, (t, f, k = !0) => { if (!f) { n((c) => { const e = t; return o(c) && o(e) && k ? y({ ...c }, e) : e; }); return; } f && n((c) => { if (!o(c)) return console.warn( `Cannot assign key-value pair. State must be of type "object", not "${typeof c}"` ), c; const e = f.split("."), p = structuredClone(c); let s = p; for (let a = 0; a < e.length - 1; a++) { const b = e[a]; o(s[b]) || (s[b] = {}), s = s[b]; } const l = e[e.length - 1]; return k && o(s[l]) && o(t) ? s[l] = y(s[l], t) : s[l] = t, p; }); }]; } export { w as useDeepState };