GithubHelp home page GithubHelp logo

troch / reinspect Goto Github PK

View Code? Open in Web Editor NEW
428.0 8.0 25.0 2.77 MB

Use redux devtools to inspect useState and useReducer :mag_right:

License: MIT License

HTML 10.94% JavaScript 12.24% TypeScript 76.82%

reinspect's Introduction

reinspect

Under development

Connect React state hooks (useState and useReducer) to redux dev tools.

See it live

useState with Redux dev tools

Why?

Hooks are great, they are a joy to use to create state in components. On the other hand, with something global and centralised like Redux, we have great dev tools.

Why not both? That's exactly what this package offers: connecting useState and useReducer to redux dev tools, so you can do the following:

  • Inspect actions and state for each hook
  • Time travel through state changes in your app
  • Hot reloading: save your current state and re-inject it when re-rendering

API

You need redux devtools installed. This package provides:

  • StateInspector: a provider which will be used by useState and useReducer to connect them to a store and redux dev tools.

    • It accepts optionally a name (name of the store in dev tools) and initialState (if you want to start with a given state)
    • You can have more than one StateInspector in your application, hooks will report to the nearest one
    • Without a StateInspector, useState and useReducer behave normally
    import React from "react"
    import { StateInspector } from "reinspect"
    import App from "./App"
    
    function AppWrapper() {
        return (
            <StateInspector name="App">
                <App />
            </StateInspector>
        )
    }
    
    export default AppWrapper
  • useState(initialState, id?): like useState but with a 2nd argument id (a unique ID to identify it in dev tools). If no id is supplied, the hook won't be connected to dev tools.

    import React from "react"
    import { useState } from "reinspect"
    
    export function CounterWithUseState({ id }) {
        const [count, setCount] = useState(0, id)
    
        return (
            <div>
                <button onClick={() => setCount(count - 1)}>-</button>
                {count} <button onClick={() => setCount(count + 1)}>+</button>
            </div>
        )
    }
  • useReducer(reducer, initialState, initializer?, id?): like useReducer but with a 4th argument id (a unique ID to identify it in dev tools). If no id is supplied, the hook won't be connected to dev tools. You can use identity function (state => state) as 3rd parameter to mock lazy initialization.

reinspect's People

Contributors

blackfenix2 avatar jamestalmage avatar pau1fitz avatar troch avatar vadistic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reinspect's Issues

Crashes when Redux Devtools Chrome extension is not installed

When I view my app with the Redux Devtools Chrome extension installed, it works fine. I use useReducer, and see the events showing up in the devtools as I'd expect.

When the extension is not installed, I get a crash. I haven't been able to fully diagnose the issue, but it is problematic that this line returns null:

// function useReducer compiled source

var store = useContext(StateInspectorContext); // ==> null

The full stack trace is:

Uncaught TypeError: Cannot read property 'getState' of null
    at index.es.js:104
    at mountMemo (react-dom.development.js:13964)
    at Object.useMemo (react-dom.development.js:14185)
    at useMemo (react.development.js:1525)
    at useHookedReducer (index.es.js:103)
    at useReducer (index.es.js:165)
    at useBuildDetails (useBuildDetails.ts:80)
    at BuildDetails (BuildDetails.tsx:35)
    at renderWithHooks (react-dom.development.js:13449)
    at mountIndeterminateComponent (react-dom.development.js:15605)
    at beginWork (react-dom.development.js:16238)
    at performUnitOfWork (react-dom.development.js:20279)
    at workLoop (react-dom.development.js:20320)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at replayUnitOfWork (react-dom.development.js:19503)
    at renderRoot (react-dom.development.js:20433)
    at performWorkOnRoot (react-dom.development.js:21357)
    at performWork (react-dom.development.js:21267)
    at performSyncWork (react-dom.development.js:21241)
    at requestWork (react-dom.development.js:21096)
    at scheduleWork (react-dom.development.js:20909)
    at scheduleRootUpdate (react-dom.development.js:21604)
    at updateContainerAtExpirationTime (react-dom.development.js:21630)
    at updateContainer (react-dom.development.js:21698)
    at ReactRoot.push../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render (react-dom.development.js:22011)
    at react-dom.development.js:22163
    at unbatchedUpdates (react-dom.development.js:21486)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:22159)
    at Object.render (react-dom.development.js:22234)
    at Module../src/index.tsx (index.tsx:7)
    at __webpack_require__ (bootstrap:781)
    at fn (bootstrap:149)
    at Object.0 (serviceWorker.js:135)
    at __webpack_require__ (bootstrap:781)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

I am not able to repro this issue with a freshly created create-react-app, nor with your demo, so clearly something in my app (which I'm not able to share) is contributing to this issue. So, do what you will with this report. ๐Ÿ˜„

Live demo is broken

The live demo codesandbox shows this error:

Could not fetch dependencies, please try again in a couple seconds: Could not fetch version for reinspect@file:../dist: ENOENT: no such file or directory, open '/var/dist/package.json'

In package.json the module's version number seems wrong "reinspect": "file:../dist".

It works for me if I leave it as an empty string, but I assume it should be the version number.

store shared between useState

If useState called with the same id from different points, then value changes are propagated between all calls.
This breaks react behavior and very inconvenient if setState is used inside custom hook.
Root of evil is useMemo. Is it really required here?

   const [store, reducerId] = useMemo<[EnhancedStore, string | number]>(
       () => [inspectorStore, id],
       []
   )

Possible solution to use generate kind of uuid if id is true or function;

Crash with useState when setState(null)

When using useState to track state in dev tool, passing "null" as argument to state setter will result in error in reinspect:
image

const App = () => {
  const [queryId, setQueryId] = useState('', 'app/queryId');
  
  useEffect(() => {
    if (queryId) {
      setQueryId(null);
    }
  }, [queryId]);

  return (<div>App</div>)

};

This is probably due to the fact that reinspect fakes a reducer call with useState.

Do not call React hooks inside other hooks or conditions

My app is complaining in the console about a hooks error:

image

But I went to investigate and my components are following the rules for hooks described in the React documentation. I looked deeper and I discovered that the errors are in your package, specifically in these lines:

const [store, reducerId] = useMemo<[EnhancedStore, string | number]>(
() => [useContext(StateInspectorContext), id],
[]
)

const [store, reducerId] = useMemo<[EnhancedStore, string | number]>(
() => [useContext(StateInspectorContext), id],
[]
)

if (!store || !reducerId) {
return useReactState<S>(initialState)
}

return store || !reducerId
? useHookedReducer(reducer, initialState, store, reducerId)
: useReactReducer<S, A>(reducer, initialState)

I tried to fix it for you but you're going to have to rewrite a part of the code.

If StateInspector is in React.StrictMode no output to redux devtools

The following works:

  <StateInspector name="App">
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </StateInspector>,

The following does not:

  <React.StrictMode>
    <StateInspector name="App">
      <App />
    </StateInspector>
  </React.StrictMode>,

Note that there is no error and the app works but there is no output in the redux devtools

'/' in id does not work

Currently it breaks.
Is it possible to fix the code in order to write
const [rows, setRows] = useState([] as TRow[], 'useTransformList/setRows')

dispatching reducer actions from devtools not working

I was trying to use the "dispatcher" functionality in the devtools work with reinspect and ran into problems.

If I try to dispatch an action that does not have a payload, I'll get the error:

"Cannot read property 'type' of undefined"

(apparently it's trying to read action.payload.type

If I dispatch an action with a payload, there's no error, but it will be ignored.

I think this should be documented or fixed

Typescript Props Type Definition for StateInspector is incompatible with `children` prop

Description

Integrating the StateInspector into a strict TypeScript react project will fail at build time.
Inserting React Nodes as a children prop into the StateInspector component will result with a TypeError.
In my specific case I was trying to insert my App component as a children prop and got an error from my IDE.

Error message

image

Code Example

import { StateInspector } from "reinspect";
import { App } from "./app";

export const AppWrapper = () => {
  return (
    <StateInspector>
      <App />
    </StateInspector>
  );
}

Suggestion

After reviewing the source code, indeed the children prop was not defined and there was no use of the PropsWithChildren type.
This is absolutely necessary in my opinion, and I am willing to provide a solution and post a pull request to fix this issue.

Discussion: Make id parameter optional

I haven't tried this yet, only read the README just now. It seems like omitting id makes the functions operate exactly as the Redux versions. If that's the case, could it be changed to use a default value so we can just change the import to get it working? Do people use multiple id values in their regular apps? Is this so useful that it's required?

Contrast this with how Redux DevTools is integrated in just once place to affect the entire application. Yes, you pepper hooks throughout your code, but having to change the imports and all call sites is a (however small) impediment to using this tool.

I was going to suggest making it the first parameter so we could curry it, but since there are only two functions providing wrappers is still trivial.

useReducer's type definition invalid: can't supply id as 3rd param

I'm not 100% if this is a bug, or a me problem, but it seems that your TS definitions imply that i can call useReducer with 3 params, and have it take the id from the 3rd param:
node_modules/reinspect/types/useReducer.d.ts

export declare function useReducer<R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, id?: string | number): [ReducerState<R>, Dispatch<ReducerAction<R>>];

But when running the code, and debugging, it looks like that isn't actually the case:
image

I assume the current 'solution'/workaround is what is referred to in the README, namely:

If no id is supplied, the hook won't be connected to dev tools. You can use identity function (state => state) as 3rd parameter to mock lazy initialization.

If that is intended as the only way to use this, then updating the type defs to disallow passing id as the 3rd param would be great.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.