Skip to content

Instantly share code, notes, and snippets.

import { useCallback, useEffect } from 'react';
import { useCancelTokens } from '../util/xhrHooks';
import { getItems as getItemsAction } from '.';
export const useItems = () => {
const addCancelToken, cancelAll } = useCancelTokens;
const getItems = useCallback(async () => {
// Cancel existing getItems requests before call a new one
cancelAll();
import { useCallback, useEffect, useRef } from 'react';
import axios, { Canceler } from 'axios';
export const useCancelTokens = () => {
const cancelTokens = useRef<Canceler[]>([]);
// Add a cancel token in this hooks and return a generated token
const addCancelToken = useCallback(() => {
const { cancel, token } = axios.CancelToken.source();
@jwchang0206
jwchang0206 / craco.config.js
Created December 3, 2020 11:48
Craco config for TypeScript with eslint-loader error fix
const CracoSwcPlugin = require('craco-swc');
module.exports = {
plugins: [
{
plugin: {
...CracoSwcPlugin,
overrideCracoConfig: ({ cracoConfig }) => {
if (typeof cracoConfig.eslint.enable !== 'undefined') {
cracoConfig.disableEslint = !cracoConfig.eslint.enable;
@jwchang0206
jwchang0206 / craco.config.js
Created December 3, 2020 11:40
Craco config for JavaScript
const CracoSwcPlugin = require('craco-swc');
module.exports = {
plugins: [
{
plugin: CracoSwcPlugin,
options: {
swcLoaderOptions: {
jsc: {
externalHelpers: true,
@jwchang0206
jwchang0206 / craco.config.js
Last active December 3, 2020 11:39
Craco config for TypeScript
const CracoSwcPlugin = require('craco-swc');
module.exports = {
plugins: [
{
plugin: CracoSwcPlugin,
options: {
swcLoaderOptions: {
jsc: {
externalHelpers: true,
import React, { useEffect, useRef } from 'react';
const Foo = () => {
const tokens = useRef([]);
useEffect(() => {
// Same as componentWillUnmount
return () => {
tokens.current.forEach(token => {
token.abort();
import React, { Component } from 'react';
class Foo {
constructor(props) {
super(props);
this.tokens = [];
}
componentWillUnmount() {
import axios, { CancelToken } from 'axios';
const source = CancelToken.source();
setTimeout(async () => {
const { data } = await axios.get(url, { cancelToken: source.token }));
alert(JSON.stringify(data));
}, 5000);
source.cancel();
const controller = new AbortController();
const { signal } = controller;
setTimeout(async () => {
const response = await fetch(url, { signal });
const data = await response.json();
alert(JSON.stringify(data));
}, 5000);
{
"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "cross-env TS_NODE_FILES=true mocha --exit --require ts-node/register --colors test/**/*.ts",
"coverage": "nyc npm run test"
},
"keywords": [],