Best JavaScript code snippet using storybook-root
useForm.ts
Source:useForm.ts
1import { useState, useContext } from 'react';2import { identity, setReducedState } from '../../utils/functions';3import { RequestParams } from '../../utils/types';4import { AppContext } from '../contexts/AppContext';56type formStateType = 'values' | 'errors' | 'both';78const formatErrors = (values: any, setErrors: any) => (9 acc: any,10 [id, func]: any,11) => {12 if (func) {13 const error = func(values[id], values, setErrors);14 if (error) {15 acc[id] = error;16 }17 }1819 return acc;20};2122export const useForm = (23 validators: any = {},24 initialValues: any = {},25 initialErrors: any = {},26) => {27 const { onRequest } = useContext<any>(AppContext);28 const [values, setValues] = useState<any>(initialValues);29 const [errors, setErrors] = useState<any>(initialErrors);3031 const validationErrors = () => Object.entries(validators).reduce(formatErrors(values, setErrors), {});3233 function onClear(type: formStateType = 'both') {34 switch (type) {35 case 'values':36 setValues({});37 break;38 case 'errors':39 setErrors({});40 break;41 default:42 setValues({});43 setErrors({});44 break;45 }46 }4748 function onSet(49 newState: any,50 type: 'values' | 'errors' = 'values',51 replace: boolean = false,52 ) {53 const prevState = type === 'values' ? values : errors;54 const accState = replace ? {} : { ...prevState };55 if (type === 'values') {56 setValues({ ...accState, ...newState });57 } else {58 setErrors({ ...accState, ...newState });59 }60 }6162 /**63 * Função para submeter qualquer tipo de formulário64 * @param endpoint - Aqui nós passamos o corpo da requisição65 * @param formatterErrors66 * @param submitValidation67 */68 async function onSubmit(69 endpoint: RequestParams,70 formatterErrors: any,71 submitValidation?: any,72 noValidation: boolean = false,73 ) {74 const formErrors = validationErrors();75 const submitErrors = submitValidation ? submitValidation(values) : {};76 try {77 if (Object.keys(formErrors).length < 1 || noValidation) {78 if (Object.keys(submitErrors).length < 1 || noValidation) {79 const resp = await onRequest(endpoint);80 return Promise.resolve(resp);81 }82 onSet(submitErrors, 'errors');83 return Promise.reject(new Error('clienterror'));84 }8586 onSet(formErrors, 'errors');87 return Promise.reject(new Error('clienterror'));88 } catch (responseErrors) {89 const isErrorJson = (responseErrors.status === 42290 || responseErrors.status === 40091 || (responseErrors.status >= 200 && responseErrors.status < 300))92 && responseErrors.status !== 204;93 const parsedErrors = isErrorJson94 ? await responseErrors.json()95 : responseErrors;96 onSet(formatterErrors(parsedErrors), 'errors');97 return Promise.reject(responseErrors);98 }99 }100101 function onChange(102 id: string | [string, number, string],103 formatter = identity,104 validate = false,105 ) {106 return (event: any) => {107 const value = formatter(event);108 if (Array.isArray(id)) {109 const [array, idx, valueId] = id;110 setValues({111 ...values,112 [array]: [113 ...values[array].slice(0, idx),114 { ...values[array][idx], [valueId]: value },115 ...values[array].slice(idx + 1),116 ],117 });118 } else {119 if (validate) {120 const validator = validators[id];121 if (validator) {122 if (validator.length === 1) {123 setErrors((errors: any) => ({124 ...errors,125 [id]: validator(value),126 }));127 } else if (validator.length === 2) {128 setErrors((errors: any) => ({129 ...errors,130 [id]: validator(value, values),131 }));132 } else {133 setErrors((errors: any) => ({134 ...errors,135 [id]: validator(value, values, setErrors),136 }));137 }138 }139 }140 setValues((values: any) => ({ ...values, [id]: value }));141 }142 };143 }144145 function onAddArray(array: string, newItem: any = {}) {146 const newItemWithId = { ...newItem, id: Date.now() };147 onSet({ [array]: [...values[array], newItemWithId] });148 }149 function onAddMultipleArray(array: string, newArray: any[] = []) {150 const newArrayWithIds = newArray.map((item: any, idx: any) => ({151 ...item,152 id: Date.now() + idx,153 }));154 onSet({ [array]: [...values[array], ...newArrayWithIds] });155 }156157 function onClearArray(array: string, idx: number | 'all') {158 if (typeof idx === 'number') {159 onSet({160 [array]: [161 ...values[array].slice(0, idx),162 { id: values[array][idx].id },163 ...values[array].slice(idx + 1),164 ],165 });166 onSet(167 { [array]: { ...errors[array], [values[array][idx].id]: '' } },168 'errors',169 );170 } else {171 onSet({172 [array]: [...values[array].map((item: any) => ({ id: item.id }))],173 });174 onSet({ [array]: {} }, 'errors');175 }176 }177178 function onDelArray(array: string, idx: number | 'all') {179 if (typeof idx === 'number') {180 onSet({181 [array]: [182 ...values[array].slice(0, idx),183 ...values[array].slice(idx + 1),184 ],185 });186 onSet(187 { [array]: { ...errors[array], [values[array][idx].id]: '' } },188 'errors',189 );190 } else {191 onSet({192 [array]: [],193 });194 onSet({ [array]: {} }, 'errors');195 }196 }197198 function onBlur(id: string) {199 return () => {200 const value = values[id];201 const validator = validators[id];202 if (validator) {203 if (validator.length === 1) {204 setErrors((errors: any) => ({205 ...errors,206 [id]: validator(value),207 }));208 } else if (validator.length === 2) {209 setErrors((errors: any) => ({210 ...errors,211 [id]: validator(value, values),212 }));213 } else {214 setErrors((errors: any) => ({215 ...errors,216 [id]: validator(value, values, setErrors),217 }));218 }219 }220 };221 }222223 function onReset(224 type: formStateType = 'both',225 retain: string | Array<string> = '',226 ) {227 switch (type) {228 case 'values':229 if (Array.isArray(retain)) {230 setReducedState(values, retain, (retainedState: any) => setValues({ ...initialValues, ...retainedState }));231 } else {232 setValues({ ...initialValues, [retain]: values[retain] });233 }234 break;235 case 'errors':236 if (Array.isArray(retain)) {237 setReducedState(errors, retain, (retainedState: any) => setErrors({ ...initialErrors, ...retainedState }));238 } else {239 setErrors({ ...initialErrors, [retain]: errors[retain] });240 }241 break;242 default:243 setValues(initialValues);244 setErrors(initialErrors);245 break;246 }247 }248249 return {250 onChange,251 validationErrors,252 onBlur,253 onClear,254 onSubmit,255 onReset,256 onAddArray,257 onAddMultipleArray,258 onClearArray,259 onDelArray,260 onSet,261 values,262 errors,263 };
...
index.js
Source:index.js
1const tryLoadAndParse = storageKey => {2 try {3 return JSON.parse(localStorage.getItem(storageKey));4 } catch {5 return undefined;6 }7}8export const retainState = storageKey => createStore => (reducer, initialState, enhancer) => {9 let actualInitialState = initialState;10 let actualEnhancer = enhancer;11 if (enhancer === undefined) {12 actualEnhancer = initialState;13 actualInitialState = undefined;14 }15 const retainedState = tryLoadAndParse(storageKey);16 const store = createStore(reducer, retainedState ?? actualInitialState, actualEnhancer);17 const unsub = store.subscribe(() => {18 const state = store.getState();19 20 try {21 localStorage.setItem(storageKey, JSON.stringify(state));22 } catch (ex) {23 unsub();24 }25 });26 return store;...
configureStore.js
Source:configureStore.js
1import {createStore, applyMiddleware, compose} from 'redux';2import rootReducer from '../reducers/common/index';3import thunk from 'redux-thunk';4import {loadState} from './retainState';5export default function configureStore(initialState){6 let retainedState = loadState();7 return createStore(8 rootReducer,9 retainedState,10 applyMiddleware(thunk)11 );...
Using AI Code Generation
1import { retainedState } from 'storybook-root';2import { retainedState } from 'storybook-root';3import { retainedState } from 'storybook-root';4import { retainedState } from 'storybook-root';5import { retainedState } from 'storybook-root';6import { retainedState } from 'storybook-root';7import { retainedState } from 'storybook-root';8import { retainedState } from 'storybook-root';9import { retainedState } from 'storybook-root';10import { retainedState } from 'storybook-root';11import { retainedState } from 'storybook-root';12import { retainedState } from 'storybook-root';13import { retainedState } from 'storybook-root';14import { retainedState } from 'storybook-root';15import { retainedState } from 'storybook-root';16import { retainedState } from 'storybook-root';17import { retainedState } from 'storybook-root';18import { retainedState } from 'storybook-root';19import { retainedState } from 'storybook-root';20import { retainedState } from 'storybook-root';
Using AI Code Generation
1import { retainedState } from 'storybook-root';2import { someState } from 'storybook-root';3import { retainedState } from 'storybook-root';4import { someState } from 'storybook-root';5import { retainedState } from 'storybook-root';6import { someState } from 'storybook-root';7import { retainedState } from 'storybook-root';8import { someState } from 'storybook-root';9import { retainedState } from 'storybook-root';10import { someState } from 'storybook-root';11import { retainedState } from 'storybook-root';12import { someState } from 'storybook-root';13import { retainedState } from 'storybook-root';14import { someState } from 'storybook-root';15import { retainedState } from 'storybook-root';16import { someState } from 'storybook-root';17import { retainedState } from 'storybook-root';18import { someState } from 'storybook-root';19import { retainedState } from 'storybook-root';
Using AI Code Generation
1import { retainedState } from '@storybook/addon-ondevice-root-provider';2import { storiesOf } from '@storybook/react-native';3storiesOf('Button', module)4 .add('with text', () => {5 return <Button onPress={action('clicked-text')}>Hello Button</Button>;6 })7 .add('with some emoji', () => {8 return (9 <Button onPress={action('clicked-emoji')}>10 );11 })12 .add('with some retained state', () => {13 const [count, setCount] = retainedState('count', 0);14 return (15 <Button onPress={() => setCount(count + 1)}>16 Count {count}17 );18 });19import { AppRegistry } from 'react-native';20import { getStorybookUI, configure } from '@storybook/react-native';21configure(() => {22 require('./test');23}, module);
Using AI Code Generation
1import { retainedState } from 'storybook-root';2export const retainedState = retainedState;3import { retainedState } from 'storybook-root';4export const retainedState = retainedState;5import { storiesOf } from '@storybook/react';6import React from 'react';7import { withKnobs } from '@storybook/addon-knobs';8import { action } from '@storybook/addon-actions';9import { MyComponent } from './MyComponent';10storiesOf('MyComponent', module)11 .addDecorator(withKnobs)12 .add('default', () => (13 <MyComponent onClick={action('clicked')} />14 ));15import { storiesOf } from '@storybook/react';16import React from 'react';17import { withKnobs, boolean } from '@storybook/addon-knobs';18import { action } from '@storybook/addon-actions';19import { MyComponent } from './MyComponent';20storiesOf('MyComponent', module)21 .addDecorator(withKnobs)22 .add('default', () => (23 <MyComponent onClick={action('clicked')} />24 .add('loading', () => (25 <MyComponent onClick={action('clicked')} loading={boolean('loading', true)} />26 ));27import { storiesOf } from '@storybook/react';28import React from 'react';29import {
Using AI Code Generation
1import { retainState } from 'storybook-root';2export default {3 parameters: {4 }5};6export const RetainState = retainState(() => {7 return <div>RetainState</div>;8});9import { addDecorator } from '@storybook/react';10export const retainState = (storyFn) => {11 addDecorator(storyFn);12 return storyFn();13};14import { retainState } from 'storybook-root';15addDecorator(retainState);16import { retainState } from 'storybook-root';17export default {18};
Using AI Code Generation
1import { retainState } from 'storybook-root';2retainState('myState', { foo: 'bar' });3import { retainState } from 'storybook-root';4storiesOf('test', module)5 .add('test', () => {6 const state = retainState('myState');7 return <div>{state.foo}</div>;8 });9import { retainState } from 'storybook-root';10storiesOf('test', module)11 .add('test', () => {12 const state = retainState('myState');13 return <div>{state.foo}</div>;14 });15import { retainState } from 'storybook-root';16storiesOf('test', module)17 .add('test', () => {18 const state = retainState('myState');19 return <div>{state.foo}</div>;20 });21import { retainState } from 'storybook-root';22storiesOf('test', module)23 .add('test', () => {24 const state = retainState('myState');25 return <div>{state.foo}</div>;26 });27import { retainState } from 'storybook-root';28storiesOf('test', module)29 .add('test', () => {30 const state = retainState('myState');31 return <div>{state.foo}</div>;32 });33import { retainState } from 'storybook-root';34storiesOf('test', module)35 .add('test', () => {36 const state = retainState('myState');37 return <div>{state.foo}</div>;38 });39import { retainState } from 'storybook-root';40storiesOf('test', module)41 .add('test', () => {42 const state = retainState('myState');43 return <div>{state.foo}</div>;44 });
Using AI Code Generation
1const { retainedState } = require('storybook-root');2const state = retainedState();3console.log(state);4const { setRetainedState } = require('storybook-root');5setRetainedState({ name: 'storybook-root' });6const { retainedState } = require('storybook-root');7const state = retainedState();8console.log(state);9const { setRetainedState } = require('storybook-root');10setRetainedState({ name: 'storybook-root' });11const { retainedState } = require('storybook-root');12const state = retainedState();13console.log(state);14const { setRetainedState } = require('storybook-root');15setRetainedState({ name: 'storybook-root' });16const { retainedState } = require('storybook-root');17const state = retainedState();18console.log(state);19const { setRetainedState } = require('storybook-root');20setRetainedState({ name: 'storybook-root' });21const { retainedState } = require('storybook-root');22const state = retainedState();23console.log(state);
Using AI Code Generation
1export const MyStory = (args) => {2 const [state, setState] = useState({});3 useEffect(() => {4 const root = document.querySelector('storybook-root');5 if (root) {6 root.retainedState = setState;7 }8 }, []);9 return <MyComponent {...args} {...state} />;10};11MyStory.args = {12};13export const MyStory = (args) => {14 const [state, setState] = useState({});15 useEffect(() => {16 const root = document.querySelector('storybook-root');17 if (root) {18 root.retainedState = setState;19 }20 }, []);21 return <MyComponent {...args} {...state} />;22};23MyStory.args = {24};25export const MyStory = (args) => {26 const [state, setState] = useState({});27 useEffect(() => {28 const root = document.querySelector('storybook-root');29 if (root) {30 root.retainedState = setState;31 }32 }, []);33 return <MyComponent {...args} {...state} />;34};35MyStory.args = {36};37export const MyStory = (args) => {38 const [state, setState] = useState({});39 useEffect(() => {40 const root = document.querySelector('storybook-root');41 if (root) {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!