How to use the preact.createContext function in preact

To help you get started, we’ve selected a few preact examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mihar-22 / preact-hooks-unistore / src / index.js View on Github external
const refEquality = (a, b) => a === b

// select('foo,bar') creates a function of the form: ({ foo, bar }) => ({ foo, bar })
const select = (properties) => {
  properties = properties.split(/\s*,\s*/)

  return state => {
    const selected = {}
    for (let i = 0; i < properties.length; i++) {
      selected[properties[i]] = state[properties[i]]
    }
    return selected
  }
}

export const StoreContext = createContext(null)

export const StoreProvider = StoreContext.Provider

export const useStore = () => useContext(StoreContext)

// selector can be a string 'foo,bar' or a function (state => state.foo)
export const useSelector = (selector, equalityFn = refEquality) => {
  const store = useStore()
  const [, forceRerender] = useReducer(s => s + 1, 0)

  const selectorRef = useRef(null)
  const selectedStateRef = useRef(null)
  const onChangeErrorRef = useRef(null)
  const isSelectorStr = (typeof selector === 'string')

  let selectedState
github preactjs / preact-render-to-string / test / render.js View on Github external
it('should work with useContext + custom value with multiple children', () => {
			let Ctx = createContext('foo');
			function Foo() {
				let v = useContext(Ctx);
				return <div>{v}</div>;
			}

			let res = render(
				
					
					
				
			);

			expect(res).to.equal('<div>bar</div><div>bar</div>');
		});
github nickvdyck / webtty / src / WebTty.UI / lib / hooks / useServices.ts View on Github external
import { createContext } from "preact"
import { useContext } from "preact/hooks"

const Context = createContext(undefined)

const useServices = (): T =&gt; {
    const services = useContext(Context)

    if (services === undefined) {
        throw new Error("No services provided")
    }
    return services as T
}

const ServiceProvider = Context.Provider

export { ServiceProvider }
export default useServices
github HenrikJoreteg / redux-bundler-preact / src / index.js View on Github external
import { Component, createContext, h } from 'preact'

export const StoreContext = createContext()

export const Provider = (props) => {
  const store = props.store
  const rest = {}
  Object.keys(props).forEach((key) => {
    if (key !== 'store') {
      rest[key] = props[key]
    }
  })

  return h(StoreContext.Provider, Object.assign({ value: store }, rest))
}

export const connect = (...args) => {
  const Comp = args.slice(-1)[0]
  const strings = args.length > 1 ? args.slice(0, -1) : []
github preactjs / preact-devtools / src / view / store / react-bindings.ts View on Github external
import { createContext } from "preact";
import { useEffect, useContext, useState, useMemo, useRef } from "preact/hooks";
import { Store } from "./types";
import { EmitFn } from "../../adapter/hook";
import { watch, Observable } from "../valoo";

export const AppCtx = createContext(null as any);
export const EmitCtx = createContext(() =&gt; null);

export const useEmitter = () =&gt; useContext(EmitCtx);
export const useStore = () =&gt; useContext(AppCtx);

export function useObserver(fn: () =&gt; T): T {
	let [_, set] = useState(0);
	let count = useRef(0);
	let tmp = useRef(null as any);
	let ref = useRef&gt;(tmp.current || (tmp.current = watch(fn)));

	const dispose = useMemo(() =&gt; {
		let disp = ref.current.on(() =&gt; {
			set((count.current = count.current + 1));
		});
		return () =&gt; {
			disp();
github JoviDeCroock / hooked-form / preact / src / helpers / context.ts View on Github external
import { createContext } from 'preact';
import { FormHookContext } from '../types';

export const formContext = createContext({} as any);
const { Consumer, Provider } = formContext;
export { Consumer, Provider };
github storeon / storeon / preact / context.js View on Github external
var Preact = require('preact')

module.exports = Preact.createContext()
github cs8425 / go-bot / admin-web / web-src / src / store.js View on Github external
import { createContext } from 'preact';

const NodeStore = createContext([]);
export { NodeStore };

const LocalStore = createContext({
	val: [],
});
export { LocalStore };

const RevStore = createContext({
	val: [],
});
export { RevStore };
github preactjs / preact-www / src / components / store-adapter.js View on Github external
import { createContext } from 'preact';
import { useContext, useLayoutEffect, useState } from 'preact/hooks';
import { mapActions } from 'unistore/src/util';

/**
 * Store context that will be passed around the app. Complex shared state
 * should be stored here.
 */
export const storeCtx = createContext();

function mapStateToProps(keys, state) {
	return keys.reduce((acc, key) => {
		acc[key] = state[key];
		return acc;
	}, {});
}

/**
 * Wire a component up to the store. Passes state as props, re-renders on change.
 * @param {string[]} keys A function mapping of store
 * state to prop values, or an array/CSV of properties to map.
 * @param {Function|Object} [actions] Action functions (pure state mappings),
 * or a factory returning them. Every action function gets current state as the
 * first parameter and any other params next
 */
github hypothesis / lms / lms / static / scripts / frontend_apps / config.js View on Github external
* @prop {GradingConfig} grading
 * @prop {Object} hypothesisClient
 * @prop {Object} rpcServer
 *   @prop {string[]} rpcServer.allowedOrigins
 * @prop {string} viaUrl
 * @prop {CanvasAuthErrorConfig} canvasOAuth2RedirectError
 */

/**
 * Configuration object for the file picker application, read from a JSON
 * script tag injected into the page by the backend.
 */

const defaultConfig = /** @type {any} */ ({ api: {} });

export const Config = createContext(
  /** @type {ConfigObject} */ (defaultConfig)
);

/**
 * Read frontend app configuration from a JSON `