New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@airma/react-effect

Package Overview
Dependencies
Maintainers
1
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@airma/react-effect

This is a react async state management tool

  • 18.3.0-alpha.11
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
21
decreased by-77.66%
Maintainers
1
Weekly downloads
 
Created
Source

npm NPM downloads standard

@airma/react-effect

@airma/react-effect is designed for managing the asynchronous effect state for react components.

Document

Why effects

Do asynchronous operations in effects is more effective.

  1. You can pre-render a default result for asynchronous operation before it is really resolved.
  2. It makes component render with less asynchronous effects spread in event handle callbacks.

If you are ready to improve your react app codes with less asynchronous operation effects, please take minutes to read the documents (中文文档) of this tool.

Basic Usage

The basic hook API useQuery and useMutation maintains a promise result state. It contains promise information data, error and status isFetching, isError for a render help.

UseQuery

This API is often used to query data with a promise returning callback and parameters for this callback. When useQuery is mounted, or the elements of parameters changed, it calls query callback.

import React from 'react';
import {useQuery} from '@airma/react-effect';
import {User} from './type';

type UserQuery = {
    name: string;
    username: string;
}
// Prepare a callback which returns a promise.
// We call it a query callback. 
const fetchUsers = (query: UserQuery):Promise<User[]> =>
        Promise.resolve([]);

const App = ()=>{
    const [query, setQuery] = useState({name:'', username:''});
    const [state, trigger, execute] = useQuery(
        // Use query callback
        fetchUsers,
        // Set parameters for query callback
        [query]
    );
    const {
        // User[] | undefined
        data,
        // boolean
        isFetching,
        // any
        error,
        // boolean
        isError,
        // boolean
        loaded
    } = state;

    ......
}

The hook API useQuery returns a tuple [state, trigger, execute]. Element state contains informations about this query action. Element trigger is a no parameter callback which returns a state promise, it should be used just like a query trigger. Element execute is a callback which accepts parameters, and returns a state promise.

If you don't want the auto query action happens, when the parameters are changed or setted first time, you should set optional config manual to stop it.

import React from 'react';
import {useQuery} from '@airma/react-effect';
import {User} from './type';

const fetchUsers = (query: UserQuery):Promise<User[]> =>
        Promise.resolve([]);

const App = ()=>{
    const [query, setQuery] = useState({name:'', username:''});
    const [state, trigger] = useQuery(
        fetchUsers,
        // Set optional config manual
        {manual: true}
    );
    const {
        // User[] | undefined
        data,
        // boolean
        isFetching,
        // any
        error,
        // boolean
        isError,
        // boolean
        loaded
    } = state;

    const handleClick = async ()=>{
        const {
          // User[] | undefined
          data,
          // boolean
          isFetching,
          // any
          error,
          // boolean
          isError,
          // boolean
          // the result might be abandoned,
          // if the execution is not the newest one.
          abandon,
          // boolean
          loaded
        } = await trigger();
    }

    ......
}

We do not recommend using the result promise returned by a trigger callback, and that's why we call it a trigger.

UseMutation

It is often used to mutate data with a promise returning callback and its parameters. It is always triggered or executed manually.

import React from 'react';
import {useMutation} from '@airma/react-effect';
import {User} from './type';

const saveUser = (user: User): Promise<User> =>Promise.resolve(user);

const App = ()=>{
    const [user, setUser] = useState({name:'', username:''});
    const [state, trigger, execute] = useMutation(
        // Provide mutation callback
        saveUser,
        // Set parameters
        [user]
    );
    const {
        // User | undefined
        data,
        // boolean
        isFetching,
        // any
        error,
        // boolean
        isError
        // boolean
        loaded
    } = state;

    const handleClick = ()=>{
        // Trigger it manually
        trigger();
    }

    ......
}

It only works in manual mode, so you don't have to worry about the auto mutation happening.

Use Strategy

Sometimes you want to control the running way about the promise callback.

For example, we often save data oncely, and then unmount component immediately after saving success to prevent a repeat saving mistake.

import React from 'react';
import {useMutation, Strategy} from '@airma/react-effect';
import {User} from './type';

const saveUser = (user:User):Promise<User> => 
    Promise.resolve(user);

const App = ()=>{
    const [user, setUser] = useState({name:'', username:''});
    const [state, trigger] = useMutation(
        saveUser,
        // Set variables and strategy
        {
        variables: [user],
        // Set Strategy.once()
        strategy: Strategy.once()
        }
    );

    const handleClick = async ()=>{
        trigger();
    }

    ......
}

Share promise state changes

There are steps you need to do for sharing promise state changes.

  1. Create a session key for every promise callback.
  2. Set session keys to SessionProvider for creating session store.
  3. Use session key to link a SessionProvider store for promise state sharing.
import React, {memo} from 'react';
import { 
  SessionProvider, 
  createSessionKey, 
  useSession, 
  useQuery 
} from '@airma/react-effect';
import {User} from './type';

const fetchLoginUser = (query:UserQuery):Promise<User>=> 
    Promise.resolve({...});

// Create a `session key`
const loginUser = createSessionKey(fetchLoginUser);

const Child1 = memo(()=>{
  // Query for current login user.
  // Update promise state into store
  // with session key `loginUser`
  const [ state ] = useQuery(loginUser,[]);

  return ......;
});

const Child2 = memo(()=>{
  // Take and subscribe promise state changes
  // of session key `loginUser` in store.
  const [ state ] = useSession(loginUser);

  return ......;
});

const App = memo(()=>{
  // Set session key `loginUser` into `SessionProvider`,
  // and create a store inside.
  return (
      <SessionProvider keys={loginUser}>
        <Child1/>
        <Child2/>
      </SessionProvider>
  );
})

Summary

The common usages about @airma/react-effect are listed above, if you want to know more about it, please take this document.

Keywords

FAQs

Package last updated on 18 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc