【问题标题】:Recoil: Set value in Atom after calling api call in SelectorRecoil:在 Selector 中调用 api 调用后在 Atom 中设置值
【发布时间】:2022-10-20 01:28:36
【问题描述】:

我想在选择器中调用 API 后在 atom 中设置值,因为我必须添加参数来调用 API。

原子

export const downloadData = atom({
  key: 'downloadData',
  default: [],
});

选择器族

export const downloadDataResultsQuery = selectorFamily<Downloads[], string[]>({
  key: 'downloadDataResultsQuery',
  get:
    (names) =>
    ({ get }) => {
      const data = get(waitForAll(names.map((name) => downloadDataResultQuery(crateName))));

      // ATTENTION: I wanna set value for `downloadData` here

      return data;
    },
});

原子家族

export const downloadDataResultsState = atomFamily<Downloads[], string[]>({
  key: 'downloadDataResultsState',
  default: (crateNames) => downloadDataResultsQuery(names),
});

我想在像const downloadDataResults = useRecoilValue(downloadDataResultsState);一样调用downloadDataResultsState之后得到不带参数的下载值,但是我找不到方法。

有没有办法做到这一点?

【问题讨论】:

  • 你解决了这个问题吗?
  • 不……我还没找到
  • 也许您可以尝试使用useRecoilCallbackselectorFamily 设置downloadData

标签: reactjs typescript recoiljs


【解决方案1】:

我以 hack 方式实现了这一点,这是我使用标签列表的代码,例如:

// the tag atom
import { atomFamily, selectFamily } from 'recoil';

export const tagState = atomFamily( {
    key : 'tag',
    default : selectorFamily( {
        key : '#tag',
        get : id => async () => {
            return getTagDataByIdFromServer();
        }
    } )
} );


// the tag list
import { selectorFamily } from 'recoil';

export cost tagListState = selectorFamily( {
    key : 'tag/list',
    get( options ) {
        return async () => getTagList( options );
    }
} );

我正在使用钩子来管理标签列表和标签数据:

import { useState, useEffect } from 'react';
import { useRecoilValue, useRecoilCallback, useRecoilRefresher_UNSTABLE as useRecoilRefresher } from 'recoil';
import { tagState, tagListState } from '.....'

export function useTagList( options ) {

    const [ safe, setSafe ] = useState( false );
    const tags = useRecoilValue( tagListState( options ) );
    const refresh = useRecoilRefresher( tagListState( options ) );
    const save = useRecoilCallback( ( { set } ) => ( id, tag ) => {
        set( tagState( id ), tag );
    } );

    useEffect( () => {
        tags.forEach( tag => { save( tag.id, tag ) } );
        setSafe( true );
    }, [ tags ] )

    return { safe, tags, refresh };
}

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2022-12-22
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多