fix for functional states

This commit is contained in:
Seth Trowbridge 2023-06-19 09:20:16 -04:00
parent 4dbc5ab1d5
commit b575ac39d4
2 changed files with 24 additions and 9 deletions

View File

@ -77,12 +77,27 @@ const ProxyState =(argNew:StateType)=>
// do we need to account for the function set?
function proxySetter (inArg:StateType)
function proxySetter ( inArg:StateType|((old:StateType)=>StateType) )
{
const stateUser = {state:inArg as StateType, set:stateSet, reload:HMR.reloads};
if(typeof inArg == "function")
{
//const passedFunction = inArg;
stateSet((oldState:StateType)=>
{
console.log("function setter intercepted");
const output = inArg(oldState);
stateUser.state = output;
HMR.statesNew.set(id, stateUser);
return output;
});
}
else
{
const stateUser = {state:inArg, set:stateSet, reload:HMR.reloads};
HMR.statesNew.set(id, stateUser);
stateSet(inArg);
}
}
return [stateGet, proxySetter];
};

View File

@ -4,18 +4,18 @@ import React from "react";
const CTXString = React.createContext("lol");
type StateBinding<T> = [get:T, set:React.StateUpdater<T>];
const CTXState = React.createContext(null) as React.Context<StateBinding<string>|null>;
const CTXState = React.createContext(null) as React.Context<StateBinding<number>|null>;
const Outer =(props:{children:VNode})=>
{
const binding = React.useState("lol?");
const binding = React.useState(11);
return <CTXState.Provider value={binding}>
{props.children}
</CTXState.Provider>
};
const Inner =()=>
{
const binding = React.useContext(CTXState);
return <button onClick={e=>binding && binding[1](Math.random().toString())}>{binding?.[0]??"(its null)"} :)</button>
const [stateGet, stateSet] = React.useContext(CTXState) || ["default", ()=>{}];
return <button onClick={e=>stateSet((old)=>old+1)}>count: {stateGet} :)</button>
};