api
docs
env
git
hbs
html
husky
jest
lintstaged
lisp
node
prettier
python
react
readme
schema
style
util
vue
web
$ tmpl react context [name]
Create a react data context under src/stores.
Files
project
└─src
└──stores
└───__tests__
└────foo.test.jsx
└───foo.jsx
↑ foo.test.jsx
import React from "react";import { fireEvent, render } from "@testing-library/react";import { FooContext, FooContextProvider, IFooContext } from "../foo";describe("FooContext", () => {describe("setValue()", () => {it("should set value to foo", () => {// Arrangeconst { getByTestId } = render(<FooContextProvider><FooContext.Consumer>{({ state, actions }: IFooContext) => {return (<><span data-testid="action" onClick={() => actions.setValue("foo")}></span><span data-testid="result">{state.value}</span></>);}}</FooContext.Consumer></FooContextProvider>);// ActfireEvent.click(getByTestId("action"));const actual = getByTestId("result").textContent;// Assertconst expected = "foo";expect(actual).toEqual(expected);});});});
↑ foo.jsx
import React, { createContext, useState } from "react";// Initexport const fooContextEmptyState = {value: ""};const emptyAction = () => {};export const fooContextEmptyActions = {setValue: () => emptyAction};export const FooContext = createContext({state: fooContextEmptyState,actions: fooContextEmptyActions});export const FooContextConsumer = FooContext.Consumer;// Implementationexport const FooContextProvider = ({ children, initialState }) => {const [state, updateState] = useState(initialState);const actions = {setValue: val => {updateState({ ...state, value: val });}};return <FooContext.Provider value={{ actions, state }}>{children}</FooContext.Provider>;};export default { FooContext, FooContextProvider };