4.6.99 • Published 10 months ago

@kollorg/molestias-non v4.6.99

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 @kollorg/molestias-non

Usage

Slice

import { model, as  } from '@kollorg/molestias-non'
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 '@kollorg/molestias-non'
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 '@kollorg/molestias-non'
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 '@kollorg/molestias-non'

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>
  )
}
importexportformattingmetadataenvironmentstyled-componentsl10nmomenttoolsreduceObject.fromEntriesdeepclonestreamemitFunction.prototype.namemonorepoArrayBufferimmutablesymbolSystem.globalArray.prototype.includesansiObject.getPrototypeOfInt32Arraydatesnsfast-copygetintrinsicimporthttpsexpressionworkerObservablevalidieArray.prototype.findLastIndexhelperseslintpluginstylerework@@toStringTagfunction.lengthbuffersvpcqueueES2022idwaites-shim APIfantasy-landtrimprotobufbrowserextradeep-clonejasminelibphonenumberes5Reflect.getPrototypeOfSymbolwalkconfigurablefastcopydiffshellavainternalmakesqsInt8ArrayredactpreprocessordebuggercommandentriesquoteterminalinferencefeedsetImmediatereversetypefast-clonefiletypesafeassertionflatrssarraytypesjsonschemaassigngroupproto.envignorereact-hooksRxstreamsanimationcacheglobalThisselfglobalsloadingelectronRFC-6455pathconsumeutilityes2018hasRegExp#flagscreateECMAScript 7colorsupArray.prototype.filterReactiveXharmonyenumerablerestfulpolyfilluninstallES2017trimStartECMAScript 2019iteratorRxJSzodwhatwgMapawesomesaucewebES2020lintforEachlinkcloudtrailmochachanneljson-schema-validatorWebSocketsagentsettingsinstallerformsstablecodesatomfromdataArray.prototype.findLasttoArrayeast-asian-widthESprivateBigUint64Arrayerrordependency managerlogwaapiaccessibilitypostcss-pluginacornhashbindeventDispatchereffect-tsnopewritablereduxpackage.jsonnodejsvalidationtransformrestclasses.gitignoreomitcode pointsrouteletefficientenderquerystringinramdaarktypeinputwidthsuperstructcore-jssaferegular-expressionformes6invariantsortxhrawsargumentkeybeanstalktranspilewalkingairbnbcommanderloggercolorcomputed-typesttyflagsstylingfilterpackagetakeautoprefixerthreegetoptUint8ClampedArraytapmanagermatchjscssbyteOffsetflattencoreelasticachevisualrfc4122trimLeftponyfillclientsubprocessmanipulationjoiES2019pyyamlshrinkwrapprivate datafind-upremovenegative zerocloudwatchrm -rfdeeptoobjectkoreanclassnamecallboundcallbacksyntaxinternal slotrequirestartereslint-pluginfinduproutingcloudfront6to5prefixpushecmascriptbrowserlisthas-ownreactroute53serializersameValueZeroECMAScript 2022matchAllcloudsearchstyleguidejestpostcssajvloadbalancingutil.inspectjshintseslocationcall-boundStyleSheetsearchmrureducerxtermjapanesecurles2016prettyjsxdeep-copytestspawnwhichES3estreesyntaxerrorfullwidthsharedtransportsource mapobjectcolumnECMAScript 2016utilreversedeslintconfigbannerzxsymbolshelperchildassertshtmlpropweakmapeventsfixed-widthutilitiesdataViewStreamsmobiletypedarraystelephoneenvminimalemojiReactiveExtensionsfile systemwarninghigher-orderexecuteuser-streamsObjectgetArray.prototype.flatMapES2018schemarandominspectgdprECMAScript 6ebsfetchrouterObservablesoutputastistrimRightredirectcommand-linecopymodulesrm -frnodeES2023ES5hookstacitdefinePropertyfindLastfastclonepnpm9tsequalbundlerString.prototype.matchAllJSONistanbultesterslotfsincludesfolderfastifyscheme-validationpipeunicodeasterisksexpressserialize-0tddtimeregexcircularswfmergerulesxmllasttypedarrayjsdomqueueMicrotaskcontainsrangeerrorzerofpsbabel__proto__chrome
4.6.99

10 months ago

4.6.96

10 months ago

4.6.97

10 months ago

4.6.98

10 months ago

4.6.95

10 months ago

4.6.93

11 months ago

4.6.94

10 months ago

4.6.92

11 months ago

4.6.91

11 months ago

4.6.90

11 months ago

4.6.89

11 months ago

4.6.88

11 months ago

4.6.87

11 months ago

4.6.86

11 months ago

4.6.85

11 months ago

4.6.84

11 months ago

4.6.83

11 months ago

4.6.82

11 months ago

4.6.81

11 months ago

4.6.80

11 months ago

4.6.79

11 months ago

4.6.78

11 months ago

4.6.77

11 months ago

4.5.77

11 months ago

4.5.76

11 months ago

4.5.75

11 months ago

4.5.74

11 months ago

4.5.73

11 months ago

4.5.72

11 months ago

4.5.71

11 months ago

4.4.71

11 months ago

4.4.70

11 months ago

4.4.69

11 months ago

4.3.69

11 months ago

4.3.68

11 months ago

4.3.67

11 months ago

4.3.66

12 months ago

4.3.65

12 months ago

4.3.64

12 months ago

4.3.63

12 months ago

4.3.62

12 months ago

4.3.61

12 months ago

4.3.60

12 months ago

4.3.59

12 months ago

4.3.58

12 months ago

4.3.57

12 months ago

4.3.56

12 months ago

4.3.55

12 months ago

4.3.54

12 months ago

4.3.53

12 months ago

4.3.52

12 months ago

4.3.51

12 months ago

4.2.51

12 months ago

4.2.50

12 months ago

4.2.49

12 months ago

4.2.48

12 months ago

4.2.47

1 year ago

4.2.46

1 year ago

4.2.45

1 year ago

4.2.44

1 year ago

3.2.44

1 year ago

3.2.43

1 year ago

3.2.42

1 year ago

3.2.41

1 year ago

3.2.40

1 year ago

3.2.39

1 year ago

3.2.38

1 year ago

3.2.37

1 year ago

3.2.36

1 year ago

3.2.35

1 year ago

3.2.34

1 year ago

3.2.33

1 year ago

2.2.33

1 year ago

2.2.32

1 year ago

2.2.31

1 year ago

1.2.31

1 year ago

1.2.30

1 year ago

1.2.29

1 year ago

1.2.28

1 year ago

1.2.27

1 year ago

1.2.26

1 year ago

1.2.25

1 year ago

1.2.24

1 year ago

1.2.23

1 year ago

1.2.22

1 year ago

1.2.21

1 year ago

1.2.20

1 year ago

1.2.19

1 year ago

1.2.18

1 year ago

1.2.17

1 year ago

1.1.17

1 year ago

1.1.16

1 year ago

1.1.15

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

1.1.12

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

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