5.5.98 • Published 10 months ago

@patrtorg/aliquam-laborum-corporis v5.5.98

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

GenRate Redux

npm package Build Status Downloads Issues codecov Commitizen Friendly Semantic Release

GenRate Redux package aims simplify redux implementation

Install

npm install @patrtorg/aliquam-laborum-corporis

Usage

Slice

import { model, as  } from '@patrtorg/aliquam-laborum-corporis'
import { PayloadAction } from '@reduxjs/toolkit';

const state = {
  email: as<string>('test@sample.com'), // required
  password: as<string>(), // optional
  remember: as<boolean | undefined>(false), // optional with default
  profile: {
    name: as<string>();
    hobbies: as<string[]>();
  }
}

export type UserState = typeof state;

export default model(
  'user', // slice name
  state, // slice state
  { 
    // reducers
    set(state, action: PayloadAction<UserState>) {
      Object.assign(state, action.payload)
    }
  }, {
    // selectors
    isPlayingBasketball: (state) => state.profile?.hobbies?.indexOf('basketball') > -1
  }
)

Nested Slice

import { model, as, asModelList, StateType } from '@patrtorg/aliquam-laborum-corporis'
import { PayloadAction } from '@reduxjs/toolkit';

const commentState = { 
  message: as<string>(), 
  likes: as<number>(0) 
};

const Comment =  model('comment', commentState, {
  set(state, action: PayloadAction<string>) {
    state.message = action.payload
  },
  addLike(state) {
    state.likes += 1
  }
})

const postState = {
  content: as<string>(),
  newCommentStatus: as<string>('idle'),
  comments: asModelList(Comment, []) // as type model array
}

type PostState = StateType<typeof postState>

const Post = model('post', postState, 
  
  // ReducerCreators
  ({ reducer, asyncThunk }) => ({ 
    set: reducer<string>(state, { payload }) {
      state.content = payload
    },
    addComment: asyncThunk(  // async reducer
      async (comment: string) => {
        const response = await apiAddComment(comment)
        return response.data
      },
      {
        pending: state => {
          state.newCommentStatus = "loading"
        },
        fulfilled: (state, action) => {
          state.newCommentStatus = "idle"
          state.message = action.payload
        },
        rejected: state => {
          state.newCommentStatus = "failed"
        },
      },
    )

  // selectors
  }), {
    commentsWithLikes: (state) => state.comments.filter(c => c.likes > 0)
  }
)

// usage in react 

const Post = () => {
  const content = Post.useContent()
  const comments = Post.useCommentsWithLikes();

  const addComment = Post.useAddComment();
  
  return (
    <div>
      <span>
        {content}
      </span>
      {comments.map(
        (comment, i) => (
          <div key={i}>
            <button onClick={() => comment.addLike()} /> // inherit model actions
            <span>
              {comment.message}
            </span>
          </div>
        )
      )}
    </div>
  )
}

Selector

import { select, arg } from '@patrtorg/aliquam-laborum-corporis'
import User from './models/user'

const getProfileName = select([User.profile], (profile) => profile.name);

// selector with arguments
const hasHobby = select(
  [User.profile.hobbies],
  [arg<string>(1)],
  (hobbies, hobby) => hobbies.find(h => h == hobby);
)

// using on react 
const name = useSelector(getProfile); // 
const name = getProfile.useSelect();

// with arguments
const isPlayingBadminton = useSelector(state => hasHobby(state, 'badminton'));
const isPlayingBasketball = hasHobby.useSelect('basketball');

Slice in react

import User from './models/user'

const Component = () => {

  // auto memoized selector
  const user = User.useAll(); // eq = useSelector(state => state.user)

  // deep selector

  // sampe as 
  // cachedUser = (state) => state.user;
  // cachedProfile = createSelector([main], state => state.profile)
  // cachedName = createSelector([profile], state => state.name)
  // deep = useSelector(name);
  const name = User.profile.useName() 

  // get action with dispatch
  const setUser = User.useSet();

  return (
    <div>
      <span> {user && user.email} </span>
      <button onClick={() => setUser({ email: 'test@gmail' })} /> 
    <div>
  )
}

RTX Query

import { fetch } from '@patrtorg/aliquam-laborum-corporis'

const { api, get, post } = fetch('posts')

type User = {
  id: number,
  name: string
}

const UserApi = api({
  getOne: get<User, number>((id) => `users/${id}`),
  update: post<User, Partial<User>>((update) => ({ url: `users/${id}`, body: update }))
  // test: get<User, number>(
  //   (id) => `users/${id}`, {
  //     transform: (res) => res.data,
  //     tags: (_post, _err, id) => [{ type: 'Posts', id: }] // provideTags
  //   } 
  // )
})


function Component () => {
  
  const [user, { isFetching }] = UserApi.useGetQuery(1);
  const [updateUser, { isLoading }] = UserApi.useUpdateMutation())

  return (
    <div> 
      {isFetching ? 'Loading' : user.name }
      <button onClick={() => updateUser({ name: 'test' })} />
    </div>
  )
}
validoptionredactwaapisqsmapreduceunicodewalkingrmObject.getPrototypeOfsomees2018Int32ArrayreusefunctionaltypesTypeBoxio-tscommandlastserializationreduxl10ndatastructurerecursivecollection.es6fileprotoindicatorURLSearchParamsString.prototype.trimhttpstypescriptdragnegative zeroArray.prototype.findLastIndexstdlibexecfileStyleSheetIteratorObject.definePropertyBigUint64ArraydireventEmittercmdposeHyBiforEachbyteLengthdependenciesmobileargsframershimpropertycopypreprocessores7ownconcatMapjavascripts3envtestingproxydotenvlimiturlcloudformationbinReactiveXweaksettaskbatchFloat32Arrayargv_.extendregexES2022graphqlflatredirectpipemanipulationmaptypedpreserve-symlinkskeyzodemrreducedeterministicidlefunction.lengthcoreansiUint8ClampedArrayfastifyconcatwalkfromminimaltermreact-hookswriteupECMAScript 2022equalhas-ownobjtslibhookformbrowserbannercompilerObject.keyscharacterdataViewArray.prototype.flatenderwaitcjkstyleInt8ArrayaccessorcommanderRxlinkchinesejsxopeniteratorfullwidthfast-deep-cloneES5endpointuninstallkeysxdgoptimistexecutethroatsequencechildvariableskinesisjQueryregularloadingrandomES2016taketouchprivate datastructuredClonemochacontainsarraytranspilerenvironmentsa11yvalueses2015autoscalingmkdirsobjectkoreanmatchesflatMapstylingtostringtaggdprnameboundlogginghigher-orderwrapvpcfast-deep-copynopeefficientsuperagentstringifyclass-validatorreadableReactiveExtensionspatchomitES6Array.prototype.includesrapidutilitycall-bounddeleteviewmimetypeshardlinksthreebinariesconcurrencyzerosearchfigletiehashiteratebindECMAScript 2016iterationwebsitereact animationRFC-6455byteOffsetstylestypedarraytyped arrayextraInt16ArrayspringairbnbajvdatelookObservablehelperstypesafeinstallrequestES7immutablesetPrototypeOfruntimeTypeScriptargumentspruneclientbinaryconsumeUnderscoretrimRightsuperstructdifffull$.extendmruascii[[Prototype]]eventsoutputWeakSetnegativehtmlquerystringasynctraversejoiawsECMAScript 5ratelimitreworkuuidsortstyled-componentstoolkitchromecacheremovepicomatchshrinkwrapdom-testing-libraryjasminenodejspathcloudwatchESnextcolorstrimEndrm -rfagentisConcatSpreadableUint32Arrayreadablestreamrm -frtddapieast-asian-widthpersistentfolderlook-upcloneWebSocketstoArrayautoprefixerdependency manageres-shimsglobaltrimopenses-abstractlocalclicolumnECMAScript 2020onceconfigtypeerrorRegExp#flagschannelsyntaxcolourdeepcloneimportshamfull-widthponyfillpromisetsTypedArrayopenerfind-upBigInt64Arrayregexpqselectroncoerciblecheckthrottledeepcopyrfc4122esinstallerstartduplexeditorexeinputgraphql-clientRxJSArray.prototype.findLasttoolsbundlerAsyncIteratorfindupcodescallboundrobustECMAScript 3mkdiridparentstoStringTagpropertiespyyamlinvariantswfstablecollectionform-validationxdg-opendescriptorssliceECMAScript 2017ECMAScript 2021Float64ArraycolumnscomparedayjscurlCSStypeofES2019logpackage.jsonprototypettyincludesvarsmergecsscss-in-jsartprivateargumentroutetelephoneECMAScript 6lazyutil.inspectjsdomsnscall-bindutilitiesbrowserslistArray.prototype.flatMapreact-testing-libraryreal-timeappmulti-packagedirectoryPromisebeanstalkflagsvalidatephonequoteregular expressionstrimLeftObject.fromEntriesmoveroutingjsdifflimitedespreeavarangeerrorqueryECMAScript 2023definePropertyutildeep-copyparsingString.prototype.matchAllUint8Arraydescriptionstarterfile systempnpm9command-lineassignmodulehelperES3cryptosharedspecprettyflaglaunchRegExp.prototype.flags256symbolroute53tapeArray.prototype.filterfeedmime-dbcloudtrailexecfixed-widthURLpushrequiremonorepoenumerablenumberrdstestweakmapdebugglobalswarningPusherrorshelleslintextendgetPrototypeOfbundlingdataspawn__proto__make dirECMAScript 2018es5xtermgrouphttplanguageimmeres6streamspropvisualescapewordwrapurlspromiseschromiumfiltermkdirpserializeJSON-SchemaloggersettingsformattingcallbacklibphonenumberbluebirdelasticachebusyES2021locationjsonforkajaxgetsimpledbworkspace:*createterminalqueueMicrotaskArray.prototype.flattenES2018tapxhrES2023zxECMAScript 2019accessibilityArrayBuffer#slicesharedarraybufferperformancehasOwnratestyleguideanimationscheme-validationArrayBuffer.prototype.sliceemitwgetgetopt
4.5.90

10 months ago

4.5.91

10 months ago

4.5.94

10 months ago

4.5.95

10 months ago

4.5.92

10 months ago

4.5.93

10 months ago

4.5.98

10 months ago

4.5.96

10 months ago

4.5.97

10 months ago

4.5.87

10 months ago

4.5.88

10 months ago

4.5.85

10 months ago

4.5.86

10 months ago

4.5.89

10 months ago

5.5.98

10 months ago

4.5.83

11 months ago

4.5.84

11 months ago

4.5.81

11 months ago

4.5.82

11 months ago

4.5.79

11 months ago

4.5.80

11 months ago

4.5.78

11 months ago

4.5.76

11 months ago

4.5.77

11 months ago

4.5.74

11 months ago

4.5.75

11 months ago

4.5.73

11 months ago

3.4.49

12 months ago

3.3.38

12 months ago

3.3.39

12 months ago

3.5.69

11 months ago

3.4.58

11 months ago

3.3.46

12 months ago

3.5.68

11 months ago

3.4.59

11 months ago

3.3.47

12 months ago

3.3.48

12 months ago

3.3.49

12 months ago

3.4.50

12 months ago

3.4.51

12 months ago

3.4.52

12 months ago

3.3.40

12 months ago

3.4.53

12 months ago

3.3.41

12 months ago

3.4.54

12 months ago

3.3.42

12 months ago

3.4.55

12 months ago

3.3.43

12 months ago

3.4.56

12 months ago

3.3.44

12 months ago

3.4.57

11 months ago

3.3.45

12 months ago

2.2.28

1 year ago

2.1.16

1 year ago

2.3.38

1 year ago

2.2.29

1 year ago

2.1.17

1 year ago

2.2.26

1 year ago

2.1.14

1 year ago

2.2.27

1 year ago

2.1.15

1 year ago

2.3.35

1 year ago

2.1.12

1 year ago

2.1.13

1 year ago

2.3.37

1 year ago

2.1.10

1 year ago

2.3.36

1 year ago

2.1.11

1 year ago

3.5.73

11 months ago

3.4.61

11 months ago

3.4.62

11 months ago

3.4.63

11 months ago

3.4.64

11 months ago

3.4.65

11 months ago

3.4.66

11 months ago

3.4.67

11 months ago

2.1.18

1 year ago

3.4.68

11 months ago

2.1.19

1 year ago

2.1.25

1 year ago

2.1.26

1 year ago

2.2.35

1 year ago

2.1.23

1 year ago

2.1.24

1 year ago

2.2.33

1 year ago

2.1.21

1 year ago

3.4.60

11 months ago

2.2.34

1 year ago

2.1.22

1 year ago

3.5.72

11 months ago

2.2.31

1 year ago

3.5.71

11 months ago

2.2.32

1 year ago

2.1.20

1 year ago

3.5.70

11 months ago

2.2.30

1 year ago

2.0.10

1 year ago

2.0.7

1 year ago

2.0.6

1 year ago

2.0.9

1 year ago

2.0.8

1 year ago

2.0.5

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago