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,11 +77,26 @@ const ProxyState =(argNew:StateType)=>
// do we need to account for the function set? // do we need to account for the function set?
function proxySetter (inArg:StateType) function proxySetter ( inArg:StateType|((old:StateType)=>StateType) )
{ {
const stateUser = {state:inArg, set:stateSet, reload:HMR.reloads}; const stateUser = {state:inArg as StateType, set:stateSet, reload:HMR.reloads};
HMR.statesNew.set(id, stateUser); if(typeof inArg == "function")
stateSet(inArg); {
//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
{
HMR.statesNew.set(id, stateUser);
stateSet(inArg);
}
} }
return [stateGet, proxySetter]; return [stateGet, proxySetter];

View File

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