Skip to content

Instantly share code, notes, and snippets.

@eldonwilliams
Last active December 10, 2021 18:29
Show Gist options
  • Save eldonwilliams/7d8c91c239bb467aef92ca831df86419 to your computer and use it in GitHub Desktop.
Save eldonwilliams/7d8c91c239bb467aef92ca831df86419 to your computer and use it in GitHub Desktop.
/*
CREATED BY: DEVVY/DEVTOPS
This is a react hook that allows you to create a state which will hold multiple values.
While this can be inefficient in some cases, it is useful when you don't need tons of states cluttering your code.
You can edit and use this as you'd like, but I'd appreciate if the creator tag was left in :)
P.S. : I tried to use minimal type checking, so that may give you some ~weird~ errors, or ones that don't make sense.
Feel free to edit this to add more specific checks.
*/
import { useState } from "react";
/**
* @typedef KeyValue
* @property {string} key the key the key value refers to
* @property {*} value the value that key equals/should equal
*/
/**
* This provides a way to store your state as a "Object", more specifically JSON.
* This exposes functions to mutate by key.
* @param {Object} initalState The beginning state of the.. state
*/
const useObjectState = initalState => {
if (typeof initalState !== "object") throw "useObjectState, initalState MUST be a [object].";
const [internalState, RAW_setInternalState] = useState(initalState);
/**
* A wrapped version of the RAW_setInternalState function that offers a typecheck
* @param {Object} newState
*/
const setInternalState = newState => {
if (typeof newState !== "object") throw "useObjectState, newState MUST be a [object].";
RAW_setInternalState(newState);
};
/**
* set a key of the internalState
* @param {KeyValue} inputObject A KeyValue object
*/
const setInternalStateKey = ({ key, value }) => {
var copiedState = {...internalState};
copiedState[key] = value;
setInternalState(copiedState);
};
/**
* Set the value of multiple keys at once
* @param {Array<KeyValue>} keys
*/
const setInternalStateKeys = (keys) => {
var copiedState = {...internalState};
keys.forEach(value => copiedState[value.key] = value.value);
setInternalState(copiedState);
};
/**
* A wrapped version of setInternalStateKey and setInternalStateKeys which will delegate which function to use based on the input object type
* @param {(KeyValue|Array<KeyValue>)} inputObject The input object
*/
const setState = (inputObject) => {
if (inputObject instanceof Array) {
setInternalStateKeys(inputObject);
} else {
setInternalStateKey(inputObject);
}
};
// REMOVED: return [initalState, setState];
return [internalState, setState]; // REV 1: fixed silly typo :sob:
};
export default useObjectState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment