Friday, 2 July 2021

Replicate React Context in Nodejs

I'd like to replicate the behavior of React Context in Nodejs but I'm struggling with it.

In React, by creating only one context, I can provide and consume different values in my components, depending on the value given to the <Provider/>. So the following works:

const MyContext = React.createContext(0);

const MyConsumer = () => { 
  return (
    <MyContext.Consumer>
      {value => {
        return <div>{value}</div>
      }}
    </MyContext.Consumer>
  )
}

const App = () => 
    <React.Fragment>
      <MyContext.Provider value={1}>
        <MyConsumer/>
      </MyContext.Provider>
      <MyContext.Provider value={2}>
        <MyConsumer/>
      </MyContext.Provider>
    </React.Fragment>;

ReactDOM.render(
  <App/>,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

However I have no idea how to implement this in Nodejs. I've taken a look at the source code of React Context but it does not help much... Here is what I got so far:

// context.js
export const createContext = (defaultValue: number) => {
  const context = {
    value: defaultValue,
    withContext: null,
    useContext: null,
  };
  function withContext(value: number, callback: (...args: any[]) => any) {
    context.value = value;
    return callback;
  }
  function useContext() {
    return context;
  }

  context.withContext = withContext;
  context.useContext = useContext;

  return context;
};

// functions.js
import { context } from "./index";
export function a() {
  const result = context.useContext();

  console.log(result);
}

export function b() {
  const result = context.useContext();

  console.log(result);
}

// index.js
import { createContext } from "./context";
import { a, b } from "./functions";

export const context = createContext(0);

const foo = context.withContext(1, a);
const bar = context.withContext(2, b);

console.log("foo", foo());
console.log("bar", bar());

Obviously, value is overwritten and 2 is logged twice.

Any help will be much appreciated!



from Replicate React Context in Nodejs

No comments:

Post a Comment