tmpl-cli
api
docs
env
git
hbs
html
husky
jest
lintstaged
lisp
node
prettier
python
react
Summaryreact context [name]react fc [name]react fc [name] -c contextNamereact fc [name] -m mobxStoreNamereact fc [name] -treact initreact mst [name]
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", () => {
// Arrange
const { 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>
);
// Act
fireEvent.click(getByTestId("action"));
const actual = getByTestId("result").textContent;
// Assert
const expected = "foo";
expect(actual).toEqual(expected);
});
});
});

foo.jsx

import React, { createContext, useState } from "react";
// Init
export const fooContextEmptyState = {
value: ""
};
const emptyAction = () => {};
export const fooContextEmptyActions = {
setValue: () => emptyAction
};
export const FooContext = createContext({
state: fooContextEmptyState,
actions: fooContextEmptyActions
});
export const FooContextConsumer = FooContext.Consumer;
// Implementation
export 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 };