@reduxjs/toolkit#createAsyncThunk TypeScript Examples

The following examples show how to use @reduxjs/toolkit#createAsyncThunk. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: actions.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
fetchTokenList = createAsyncThunk<TokenList, string>(
  'lists/fetchTokenList',
  (url: string) =>
    // this makes it so we only ever fetch a list a single time concurrently
    (fetchCache[url] =
      fetchCache[url] ??
      getTokenList(url).catch(error => {
        delete fetchCache[url]
        throw error
      }))
)
Example #2
Source File: account-slice.ts    From lobis-frontend with MIT License 6 votes vote down vote up
getBalances = createAsyncThunk("account/getBalances", async ({ address, networkID, provider }: IGetBalances): Promise<IAccountBalances> => {
    const sLobiContract = new ethers.Contract(addresses.lobi, abis.sLobi, provider);
    const sLobiBalance = await sLobiContract.balanceOf(address);
    const lobiContract = new ethers.Contract(addresses.sLobi, abis.lobi, provider);
    const lobiBalance = await lobiContract.balanceOf(address);

    return {
        balances: {
            sLobi: ethers.utils.formatUnits(sLobiBalance, "gwei"),
            lobi: ethers.utils.formatUnits(lobiBalance, "gwei"),
        },
    };
})
Example #3
Source File: account-slice.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
getBalances = createAsyncThunk(
  "account/getBalances",
  async ({ address, networkID, provider }: IGetBalances): Promise<IAccountBalances> => {
    const addresses = getAddresses(networkID);

    const memoContract = new ethers.Contract(addresses.SRUG_ADDRESS, SRugTokenContract, provider);
    const memoBalance = await memoContract.balanceOf(address);
    const timeContract = new ethers.Contract(addresses.RUG_ADDRESS, RugTokenContract, provider);
    const timeBalance = await timeContract.balanceOf(address);
    const duragContract = new ethers.Contract(addresses.DURAG_ADDRESS, DuragTokenContract, provider);
    const duragBalance = await duragContract.balanceOf(address);

    return {
      balances: {
        srug: ethers.utils.formatUnits(memoBalance, "gwei"),
        rug: ethers.utils.formatUnits(timeBalance, "gwei"),
        durag: ethers.utils.formatEther(duragBalance),
      },
    };
  },
)
Example #4
Source File: datasetStateSlice.ts    From prism-frontend with MIT License 6 votes vote down vote up
loadDataset = createAsyncThunk<
  TableData,
  DatasetRequestParams,
  CreateAsyncThunkTypes
>('datasetState/loadDataset', async (params: DatasetRequestParams) => {
  const results = (params as AdminBoundaryRequestParams).id
    ? loadAdminBoundaryDataset(params as AdminBoundaryRequestParams)
    : loadEWSDataset(params as EWSDataPointsRequestParams);

  return results;
})
Example #5
Source File: account-slice.ts    From wonderland-frontend with MIT License 6 votes vote down vote up
getBalances = createAsyncThunk("account/getBalances", async ({ address, networkID, provider }: IGetBalances): Promise<IAccountBalances> => {
    const addresses = getAddresses(networkID);

    const memoContract = new ethers.Contract(addresses.MEMO_ADDRESS, MemoTokenContract, provider);
    const memoBalance = await memoContract.balanceOf(address);
    const timeContract = new ethers.Contract(addresses.TIME_ADDRESS, TimeTokenContract, provider);
    const timeBalance = await timeContract.balanceOf(address);
    const wmemoContract = new ethers.Contract(addresses.WMEMO_ADDRESS, wMemoTokenContract, provider);
    const wmemoBalance = await wmemoContract.balanceOf(address);

    return {
        balances: {
            memo: ethers.utils.formatUnits(memoBalance, "gwei"),
            time: ethers.utils.formatUnits(timeBalance, "gwei"),
            wmemo: ethers.utils.formatEther(wmemoBalance),
        },
    };
})
Example #6
Source File: collectionSlice.ts    From aqualink-app with MIT License 6 votes vote down vote up
collectionRequest = createAsyncThunk<
  CollectionState["details"],
  CollectionRequestParams,
  CreateAsyncThunkTypes
>(
  "collection/request",
  async ({ id, isHeatStress, isPublic, token }, { rejectWithValue }) => {
    try {
      if (isHeatStress && !id) {
        const { data } = await collectionServices.getHeatStressCollection();
        return constructCollection(data);
      }
      if (id) {
        const { data } = isPublic
          ? await collectionServices.getPublicCollection(id)
          : await collectionServices.getCollection(id, token);
        return constructCollection(data);
      }
      return undefined;
    } catch (err) {
      return rejectWithValue(getAxiosErrorMessage(err));
    }
  }
)
Example #7
Source File: slice.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
initNotes = createAsyncThunk(
  "engine/init",
  async ({ url, ws }: { url: string; ws: string }, { dispatch }) => {
    const logger = createLogger("initNotesThunk");
    const endpoint = url;
    const api = new DendronApiV2({
      endpoint,
      apiPath: "api",
      logger,
    });
    logger.info({ state: "pre:workspaceSync" });
    const resp = await api.workspaceSync({ ws });
    logger.info({ state: "post:workspaceSync" });
    if (resp.error) {
      dispatch(setError(stringifyError(resp.error)));
      return resp;
    }
    const data = resp.data!;
    logger.info({ state: "pre:setNotes" });
    dispatch(setFromInit(data));
    dispatch(setError(undefined));
    logger.info({ state: "post:setNotes" });
    return resp;
  }
)
Example #8
Source File: fetchWeather.ts    From react-weather-app with GNU General Public License v3.0 6 votes vote down vote up
fetchWeather = createAsyncThunk(
  'weather/fetchWeather',
  async (city: string | { lat: number; lng: number }, { dispatch, rejectWithValue, fulfillWithValue }) => {
    dispatch(setIsLoading(true));

    try {
      const res = await Promise.all([fetchWeatherData(city), fetchExtendedForecastData(city)]);
      dispatch(setIsLoading(false));

      if (res[0].cod === 200) {
        dispatch(setIsInitial(false));
        return res;
      }
      return rejectWithValue(res[0].message);
    } catch {
      dispatch(setIsLoading(false));
      return rejectWithValue('Error');
    }
  }
)
Example #9
Source File: location.slice.ts    From safetraceapi with GNU General Public License v3.0 6 votes vote down vote up
getNodes = createAsyncThunk<any>(
  'nodes/get',
  async (body: any, thunkApi?) => {
    const response = await fetch('https://safetraceapi.herokuapp.com/api/nodes', {
      method: 'GET',
      headers: {
        api_key: `4b6bff10-760e-11ea-bcd4-03a854e8623c`,
      },
      body,
    });

    if (response.status !== 200) {
      return thunkApi.rejectWithValue((await response.json()) as any);
    }

    return (await response.json()) as any;
  },
)
Example #10
Source File: index.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
fetchFarmsPublicDataAsync = createAsyncThunk<Farm[], number[]>(
  'farms/fetchFarmsPublicDataAsync',
  async (pids) => {
    const farmsToFetch = farmsConfig.filter((farmConfig) => pids.includes(farmConfig.pid))

    // Add price helper farms
    const farmsWithPriceHelpers = farmsToFetch.concat(priceHelperLpsConfig)

    const farms = await fetchFarms(farmsWithPriceHelpers)
    const farmsWithPrices = await fetchFarmsPrices(farms)

    // popsicle
    // Filter out price helper LP config farms
    // const farmsWithoutHelperLps = farmsWithPrices.filter((farm: Farm) => {
    //   return farm.pid || farm.pid === 0
    // })

    // return farmsWithoutHelperLps
    return farmsWithPrices
  },
)
Example #11
Source File: fitbit.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
authorizeFitbit = createAsyncThunk<Response, Arguments>(
  'fitbit/authorize',
  async (_, { rejectWithValue }) => {
    try {
      const response = await authorize(CONFIG.FITBIT_CONFIG)
      await setAccess('fitbit', {
        refreshToken: response.refreshToken,
        accessToken: response.accessToken
      })

      if (typeof response?.tokenAdditionalParameters?.user_id === 'undefined') {
        return rejectWithValue(false)
      }

      return {
        userID: response?.tokenAdditionalParameters?.user_id,
        accessTokenExpirationDate: response.accessTokenExpirationDate
      }
    } catch (error) {
      return rejectWithValue(false)
    }
  }
)
Example #12
Source File: actions.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 6 votes vote down vote up
deleteGamepadConfigAction = createAsyncThunk(
  'config/delete',
  async ({ name }: { name: string }, { getState }) => {
    const promises: Promise<any>[] = [];
    if (isConfigActive(getState(), name)) {
      // We are deleting the active config, so activate default instead
      promises.push(_setActiveConfig(DEFAULT_CONFIG_NAME, getState()));
    }
    await Promise.all([...promises, deleteGamepadConfig(name)]);
    return { name };
  },
)
Example #13
Source File: actions.ts    From jellyfin-audio-player with MIT License 6 votes vote down vote up
downloadTrack = createAsyncThunk(
    '/downloads/track',
    async (id: EntityId, { dispatch, getState }) => {
        // Get the credentials from the store
        const { settings: { jellyfin: credentials } } = (getState() as AppState);

        // Generate the URL we can use to download the file
        const url = generateTrackUrl(id as string, credentials);
        const location = `${DocumentDirectoryPath}/${id}.mp3`;

        // Actually kick off the download
        const { promise } = await downloadFile({
            fromUrl: url,
            progressInterval: 250,
            background: true,
            begin: ({ jobId, contentLength }) => {
                // Dispatch the initialization
                dispatch(initializeDownload({ id, jobId, size: contentLength }));
            },
            progress: (result) => {
                // Dispatch a progress update
                dispatch(progressDownload({ id, progress: result.bytesWritten / result.contentLength }));
            },
            toFile: location,
        });

        // Await job completion
        const result = await promise;
        dispatch(completeDownload({ id, location, size: result.bytesWritten }));
    },
)
Example #14
Source File: namespaceThunks.ts    From console with GNU Affero General Public License v3.0 6 votes vote down vote up
validateNamespaceAsync = createAsyncThunk(
  "createTenant/validateNamespaceAsync",
  async (_, { getState, rejectWithValue, dispatch }) => {
    const state = getState() as AppState;
    const namespace = state.createTenant.fields.nameTenant.namespace;

    return api
      .invoke("GET", `/api/v1/namespaces/${namespace}/tenants`)
      .then((res: any[]): boolean => {
        const tenantsList = get(res, "tenants", []);
        let nsEmpty = true;
        if (tenantsList && tenantsList.length > 0) {
          return false;
        }
        if (nsEmpty) {
          dispatch(namespaceResourcesAsync());
        }
        // it's true it's empty
        return nsEmpty;
      })
      .catch((err) => {
        dispatch(
          setModalErrorSnackMessage({
            errorMessage: "Error validating if namespace already has tenants",
            detailedError: err.detailedError,
          })
        );
        return rejectWithValue(false);
      });
  }
)
Example #15
Source File: actions.ts    From OpenBA-NextGenTV with MIT License 6 votes vote down vote up
getAlertsAsync = createAsyncThunk(
  'alert/fetchAlerts',
  async (baseURI: string | null, { rejectWithValue }) => {
    const pathToNRTData = baseURI
      ? `${baseURI}/dynamic/trigger/trigger.json`
      : 'dynamic/trigger/trigger.json';

    try {
      const response = await fetch(pathToNRTData, {
        cache: 'no-cache',
      });

      if (!response.ok) {
        throw new Error(`Cant't get Alerts`);
      }

      const alerts = await response.json();

      return { alerts, baseURI };
    } catch (err) {
      return rejectWithValue(err);
    }
  }
)
Example #16
Source File: clustersSlice.ts    From assisted-ui-lib with Apache License 2.0 6 votes vote down vote up
fetchClustersAsync = createAsyncThunk<Cluster[] | void>(
  'clusters/fetchClustersAsync',
  async () => {
    try {
      const { data } = await ClustersAPI.list();
      return data.filter((cluster) => cluster.kind === 'Cluster');
    } catch (e) {
      handleApiError(e, () => Promise.reject('Failed to fetch clusters.'));
    }
  },
)
Example #17
Source File: CounterSlice.tsx    From cra-template-typekit with MIT License 6 votes vote down vote up
fetchInitial = createAsyncThunk(
  "counter/fetchInitial",
  async (_, { rejectWithValue }) => {
    try {
      // For demo purpose let's say out value is the length
      // of the project name in manifest and the api call is slow
      await sleep();
      const response = await axios.get("/manifest.json");
      return response.data.name.length;
    } catch (err) {
      return rejectWithValue("Something went wrong.");
    }
  }
)
Example #18
Source File: AuthSlice.tsx    From knboard with MIT License 6 votes vote down vote up
register = createAsyncThunk<
  User,
  RegisterProps,
  {
    rejectValue: ValidationErrors;
  }
>("auth/registerStatus", async (credentials, { rejectWithValue }) => {
  try {
    // Don't POST blank email
    if (!credentials["email"]) {
      delete credentials["email"];
    }
    const response = await api.post(API_REGISTER, credentials);
    return response.data;
  } catch (err) {
    const error: AxiosError<ValidationErrors> = err;
    if (!error.response) {
      throw err;
    }
    return rejectWithValue(error.response.data);
  }
})