#StackBounty: #javascript #reactjs #typescript #react-native React Native check context value on click test case

Bounty: 200

I have following context

Home.tsx

export const ThemeContext = React.createContext(null)

const Home = () => {
  const { width } = Dimensions.get("window")
  const [theme, setTheme] = React.useState({
    active: 0,
    heightOfScrollView: 0,
    profileWidth: width * 0.2,
    scrolledByTouchingProfile: false
  })
  
  const horizontalScrollRef = React.useRef<ScrollView>()
  const verticalScrollRef = React.useRef<ScrollView>()

  return (
    <>
      <SafeAreaView style={styles.safeAreaContainer} />
      <Header title="Contacts" />
      <ThemeContext.Provider value={{ theme, setTheme }}>

In component A, I have a button which changes in the context

const onProfileTouched = (index: number) => {
  setTheme({ ...theme, active: index });
};

This leads to an image being active

const ImageCircle = ({ active, uri }: Props) => {
  return (
    <View
      style={
        active
          ? { ...styles.parentView, ...styles.active }
          : { ...styles.parentView }
      }>
      <Image source={uri} width={30} height={30} />
    </View>
  );
};

Now, I want to write a test case (I haven’t written a test case before) that confirms that the state has actually changed or perhaps an active border is added to the image

I added a testId to my button which I used to fire an event

it('changes active on profile clicked', () => {
  const { getByTestId } = render(<Home />);
  fireEvent.press(getByTestId('HScroll3.button'));
});

Now, I am unsure, how to grab the value of context or change in style so as I can confirm that indeed the component for which the button is pressed is active

I am using import {render, fireEvent} from '@testing-library/react-native' but open to change.


Get this bounty!!!

#StackBounty: #reactjs #typescript #spring-boot #material-ui #react-typescript Implement pagination for React Material table

Bounty: 200

I have this Spring Boot endpoint for listing items from database:

import React, { useEffect, useState } from "react";

import clsx from "clsx";
import {
  createStyles,
  lighten,
  makeStyles,
  Theme,
} from "@material-ui/core/styles";
import CircularProgress from "@material-ui/core/CircularProgress";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TablePagination from "@material-ui/core/TablePagination";
import TableRow from "@material-ui/core/TableRow";
import TableSortLabel from "@material-ui/core/TableSortLabel";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Paper from "@material-ui/core/Paper";
import Checkbox from "@material-ui/core/Checkbox";
import IconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
import DeleteIcon from "@material-ui/icons/Delete";
import FilterListIcon from "@material-ui/icons/FilterList";
import axios, { AxiosResponse } from "axios";
import { getTask } from "../../service/merchants";

const baseUrl = "http://185.185.126.15:8080/api";

interface OnboardingTaskDto {
  id?: number;
  name: string;
}

async function getTask(
  page: number,
  size: number
): Promise<AxiosResponse<OnboardingTaskDto[]>> {
  return await axios.get<OnboardingTaskDto[]>(
    `${baseUrl}/management/onboarding/task?page=${page}&size=${size}`
  );
}

interface Data {
  id: number;
  businessName: string;
  title: string;
  status: string;
}

function createData(
    id: number,
    businessName: string,
    title: string,
    status: string
): Data {
  return { id, businessName, title, status };
}

function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

type Order = "asc" | "desc";

function getComparator<Key extends keyof any>(
    order: Order,
    orderBy: Key
): (
    a: { [key in Key]: number | string },
    b: { [key in Key]: number | string }
) => number {
  return order === "desc"
      ? (a, b) => descendingComparator(a, b, orderBy)
      : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) {
  const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

interface HeadCell {
  disablePadding: boolean;
  id: keyof Data;
  label: string;
  numeric: boolean;
}

const headCells: HeadCell[] = [
  { id: "id", numeric: false, disablePadding: true, label: "id" },
  {
    id: "businessName",
    numeric: true,
    disablePadding: false,
    label: "businessName",
  },
  { id: "title", numeric: true, disablePadding: false, label: "title" },
  { id: "status", numeric: true, disablePadding: false, label: "status" },
];

interface EnhancedTableProps {
  classes: ReturnType<typeof useStyles>;
  numSelected: number;
  onRequestSort: (
      event: React.MouseEvent<unknown>,
      property: keyof Data
  ) => void;
  onSelectAllClick: (event: React.ChangeEvent<HTMLInputElement>) => void;
  order: Order;
  orderBy: string;
  rowCount: number;
}

function EnhancedTableHead(props: EnhancedTableProps) {
  const {
    classes,
    onSelectAllClick,
    order,
    orderBy,
    numSelected,
    rowCount,
    onRequestSort,
  } = props;
  const createSortHandler =
      (property: keyof Data) => (event: React.MouseEvent<unknown>) => {
        onRequestSort(event, property);
      };

  return (
      <TableHead>
        <TableRow>
          <TableCell padding="checkbox">
            <Checkbox
                indeterminate={
                  numSelected > 0 && numSelected < rowCount
                }
                checked={rowCount > 0 && numSelected === rowCount}
                onChange={onSelectAllClick}
                inputProps={{ "aria-label": "select all desserts" }}
            />
          </TableCell>
          {headCells.map((headCell) => (
              <TableCell
                  key={headCell.id}
                  align={headCell.numeric ? "right" : "left"}
                  padding={headCell.disablePadding ? "none" : "normal"}
                  sortDirection={orderBy === headCell.id ? order : false}
              >
                <TableSortLabel
                    active={orderBy === headCell.id}
                    direction={orderBy === headCell.id ? order : "asc"}
                    onClick={createSortHandler(headCell.id)}
                >
                  {headCell.label}
                  {orderBy === headCell.id ? (
                      <span className={classes.visuallyHidden}>
                                    {order === "desc"
                                        ? "sorted descending"
                                        : "sorted ascending"}
                                </span>
                  ) : null}
                </TableSortLabel>
              </TableCell>
          ))}
        </TableRow>
      </TableHead>
  );
}

const useToolbarStyles = makeStyles((theme: Theme) =>
    createStyles({
      root: {
        paddingLeft: theme.spacing(2),
        paddingRight: theme.spacing(1),
      },
      highlight:
          theme.palette.type === "light"
              ? {
                color: theme.palette.secondary.main,
                backgroundColor: lighten(
                    theme.palette.secondary.light,
                    0.85
                ),
              }
              : {
                color: theme.palette.text.primary,
                backgroundColor: theme.palette.secondary.dark,
              },
      title: {
        flex: "1 1 100%",
      },
    })
);

interface EnhancedTableToolbarProps {
  numSelected: number;
  onClick: (e: React.MouseEvent<unknown>) => void;
}

const EnhancedTableToolbar = (props: EnhancedTableToolbarProps) => {
  const classes = useToolbarStyles();
  const { numSelected } = props;

  return (
      <Toolbar
          className={clsx(classes.root, {
            [classes.highlight]: numSelected > 0,
          })}
      >
        {numSelected > 0 ? (
            <Typography
                className={classes.title}
                color="inherit"
                variant="subtitle1"
                component="div"
            >
              {numSelected} selected
            </Typography>
        ) : (
            <Typography
                className={classes.title}
                variant="h6"
                id="tableTitle"
                component="div"
            >
              Customers
            </Typography>
        )}
        {numSelected > 0 ? (
            <Tooltip title="Delete">
              <IconButton aria-label="delete" onClick={props.onClick}>
                <DeleteIcon />
              </IconButton>
            </Tooltip>
        ) : (
            <Tooltip title="Filter list">
              <IconButton aria-label="filter list">
                <FilterListIcon />
              </IconButton>
            </Tooltip>
        )}
      </Toolbar>
  );
};

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
      root: {
        width: "100%",
      },
      paper: {
        width: "100%",
        marginBottom: theme.spacing(2),
      },
      table: {
        minWidth: 750,
      },
      visuallyHidden: {
        border: 0,
        clip: "rect(0 0 0 0)",
        height: 1,
        margin: -1,
        overflow: "hidden",
        padding: 0,
        position: "absolute",
        top: 20,
        width: 1,
      },
    })
);

export default function BusinessCustomersTable() {
  const classes = useStyles();
  const [order, setOrder] = React.useState<Order>("asc");
  const [orderBy, setOrderBy] = React.useState<keyof Data>("businessName");
  const [selected, setSelected] = React.useState<number[]>([]);
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(5);
  const [rows, setRows] = useState<Data[]>([]);
  const [loading, setLoading] = useState(false);

  let updatedState: Data[] = [];

  // TODO - move this to API file
  const apiUrl = "http://185.185.126.15:8080/api/management/onboarding/task";

  useEffect(() => {
    const getData = async () => {
      setLoading(true);

      getTask(1, 100)
          .then((resp) => {
            console.log(resp.data);
          })
          .catch((error) => {
            console.error(error);
          });
      const response = await axios.get(apiUrl, {
        params: { page: 1, size: 100 },
      });
      setLoading(false);

      const objContent: any = response.data.content;

      for (let a = 0; a < objContent.length; a++) {
        updatedState[a] = createData(
            objContent[a].id,
            objContent[a].businessName,
            objContent[a].title,
            objContent[a].status
        );

        setRows([...rows, ...updatedState]);
      }
    };

    getData();
  }, []);

  const handleRequestSort = (
      event: React.MouseEvent<unknown>,
      property: keyof Data
  ) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleSelectAllClick = (
      event: React.ChangeEvent<HTMLInputElement>
  ) => {
    if (event.target.checked) {
      const newSelecteds = rows.map((n) => n.id);
      setSelected(newSelecteds);
      return;
    }
    setSelected([]);
  };

  const handleClick = (event: React.MouseEvent<unknown>, id: number) => {
    const selectedIndex = selected.indexOf(id);
    let newSelected: number[] = [];

    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, id);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
          selected.slice(0, selectedIndex),
          selected.slice(selectedIndex + 1)
      );
    }

    setSelected(newSelected);
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
      event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleDeleteClick = async () => {
    // npm install qs
    var qs = require("qs");

    const response = await axios.delete(apiUrl, {
      params: {
        ids: selected,
      },
      paramsSerializer: (params) => {
        return qs.stringify(params);
      },
    });

    if (response.status === 204) {
      const updatedData = rows.filter(
          (row) => !selected.includes(row.id)
      ); // It'll return all data except selected ones

      setRows(updatedData); // reset rows to display in table.
    }
  };

  const isSelected = (id: number) => selected.indexOf(id) !== -1;

  const emptyRows =
      rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

  return (
      <div className={classes.root}>
        <Paper className={classes.paper}>
          <EnhancedTableToolbar
              numSelected={selected.length}
              onClick={handleDeleteClick}
          />
          <TableContainer>
            <Table
                className={classes.table}
                aria-labelledby="tableTitle"
                aria-label="enhanced table"
            >
              <EnhancedTableHead
                  classes={classes}
                  numSelected={selected.length}
                  order={order}
                  orderBy={orderBy}
                  onSelectAllClick={handleSelectAllClick}
                  onRequestSort={handleRequestSort}
                  rowCount={rows.length}
              />
              <TableBody>
                {loading ? (
                    <div className="spinerr">
                      <CircularProgress />
                    </div>
                ) : null}
                {stableSort(rows, getComparator(order, orderBy))
                    .slice(
                        page * rowsPerPage,
                        page * rowsPerPage + rowsPerPage
                    )
                    .map((row, index) => {
                      const isItemSelected = isSelected(row.id);
                      const labelId = `enhanced-table-checkbox-${index}`;

                      return (
                          <TableRow
                              hover
                              onClick={(event) =>
                                  handleClick(event, row.id)
                              }
                              role="checkbox"
                              aria-checked={isItemSelected}
                              tabIndex={-1}
                              key={row.businessName}
                              selected={isItemSelected}
                          >
                            <TableCell padding="checkbox">
                              <Checkbox
                                  checked={isItemSelected}
                                  inputProps={{
                                    "aria-labelledby":
                                    labelId,
                                  }}
                              />
                            </TableCell>
                            <TableCell
                                component="th"
                                id={labelId}
                                scope="row"
                                padding="none"
                            >
                              {row.id}
                            </TableCell>
                            <TableCell align="right">
                              {row.businessName}
                            </TableCell>
                            <TableCell align="right">
                              {row.title}
                            </TableCell>
                            <TableCell align="right">
                              {row.status}
                            </TableCell>
                          </TableRow>
                      );
                    })}
                {emptyRows > 0 && (
                    <TableRow style={{ height: 53 * emptyRows }}>
                      <TableCell colSpan={6} />
                    </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
              rowsPerPageOptions={[5, 10, 25]}
              component="div"
              count={rows.length}
              rowsPerPage={rowsPerPage}
              page={page}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
          />
        </Paper>
      </div>
  );
}

Sandbox: https://stackblitz.com/edit/react-ts-tnpk85?file=Hello.tsx

When data is loaded first time and I switch pages I don’t see additional requests to Back end. Looks like data table rows data is loaded only once. I need to implement a lazy pagination and load current page data when I switch page. Do you know how I can fix this?


Get this bounty!!!

#StackBounty: #javascript #reactjs #typescript React type error "not assignable to parameter of type 'never'"

Bounty: 50

What I want to do is loop over current posttype and ‘products’ but I’m always struggle with the types. So I got the following error:

Argument of type ‘Record<string, any>[]’ is not assignable to parameter of type ‘never’.

On part this part:

...pages.map((page) => ({

Here is my code:

    const pages = useSelect((select) => {
    const editor = select('core/editor');
    const currentPostType: string = editor.getCurrentPostType();
    const selectablePostTypes = [currentPostType, 'products'];

    const postList = [];

    selectablePostTypes.forEach((singlePostType) => {
      const records: Record<string, any>[] = select('core').getEntityRecords(
        'postType',
        singlePostType,
      );

      postList.push(records);
    });
  });

  // Make dropdown of pagesOptions
  const pagesOptions = [
    ...[
      {
        value: '0',
        label: __('No page selected', 'demosite'),
      },
    ],
    ...pages.map((page) => ({
      value: page.id,
      label: page.title,
    })),
  ];

Add the code part which works:

      const pages = useSelect((select) => {
    const editor = select('core/editor');
    const postType: string = editor.getCurrentPostType();
    const records: Record<string, any>[] = select('core').getEntityRecords(
      'postType',
      postType,
    );

    return records ?
      records.map((record) => ({
        description: record.description,
        id: record.id,
        featuredMedia: record.featuredMedia,
        link: record.link,
        subtitle: record.subtitle,
        title: record.title.rendered,
      })) :
      [];
  });

But here it is targeted on one post type, the post-type your editing right now. But I want to loop this over some posttypes.

examples:

const selectablePostTypes = ['page', 'post', 'product'];


Get this bounty!!!

#StackBounty: #angular #typescript #intro.js Why does Intro js element selection not work in mat card

Bounty: 50

I have created a tour, added step and ids to elements. But a element that is nested in, is an angular component or is from a library that is for angular will not be highlighted.

This is my tour:

this.introJS.setOptions({
      tooltipClass: 'customTooltip',
      highlightClass: 'customHighlight',
      exitOnOverlayClick: false,
      disableInteraction: false,
      steps: [
        {
          intro: 'Welcome to the web let me show you around!',
        },
        {
          element: '#step2',
          intro: 'Go to Home',
          position: 'right'
        },
        {
          element: document.getElementById('step3'),
          intro: 'Fill out the form',
          position: 'right'
        },
        {
          element: document.querySelector('#step4'),
          intro: 'Click Create an account',
          position: 'right'
        }
      ]
    }).start();

This is the html:

<div>
  <mat-card>
    <mat-card-content>
      <form id="step3" [formGroup]="testForm">
        <h3>test</h3>
          <mat-form-field appearance="outline">
            <mat-label>label</mat-label>
            <mat-select formControlName="role">
              <mat-option>1</mat-option>
            </mat-select>
          </mat-form-field>
      </form>
    </mat-card-content>
  </mat-card>
</div>

This is what the tip looks like:
enter image description here

It’s in the centre and doesn’t highlight anything

Edit:
If CyC0der’s answer is correct then I have problem with using the ngnIntroService. I can’t seem to get it included correctly. I created another question just for that issue here.


Get this bounty!!!

#StackBounty: #javascript #typescript #react-native #deep-linking #branch.io How to navigate from linking (deep linking with branch.io)…

Bounty: 50

I pretty much followed both react-navigation deep linking and branch.io react-native documentation, and either both are deprecated or just not completely helpful.

All I want is that whenever a deep link reads from the linking, navigate to a certain screen, I’m not looking to implement a listener on a specific screen, I want this on a root path, and is either the onReady (which for me didn’t work) or linking from navigator container

this is my code, very simple

const linking: LinkingOptions = {
  prefixes: ['agendameio://', 'https://agendame.io', 'https://agendameio.app.link', 'https://agendameio.app-alternative.link'],
  subscribe(listener) {
    const navigation = useNavigation();
    const onReceiveURL = ({ url }: { url: string }) => listener(url);
    Linking.addEventListener('url', onReceiveURL);
    branch.skipCachedEvents();
    branch.subscribe(async ({ error, params, uri }) => {
      if (error) {
        console.error('Error from Branch: ' + error);
        return;
      }
      if (params) {
        DataManager.DynamicURL = params['~id'] === "951933826563912687" ? params.id : undefined;
      }
      let url = params?.['+url'] || params?.['~referring_link']; // params !== undefined ? `agendameio://empresa/${params.id}` : 'agendameio://empresa';
      navigation.navigate(`DetalleEmpresa${params.id}`);
      listener(url);
    });
    return () => {
      Linking.removeEventListener('url', onReceiveURL);
      branch.logout();
    };
  },

I instantly get an error due to use navigation, but I really don’t know what else to use to navigate to inside the app

EDIT: this is the error in particular

Error

EDIT 2: I’ll add my navigation so it can help to understand my problem

function firstStack() {
  return (
    <homeStack.Navigator initialRouteName="EmpresasScreen">
      <homeStack.Screen
        options={({navigation}) => ({
          headerShown: false,
          headerTitle: () => (
            <>
              <View style={styles.viewHeader}>
                <Image 
                  resizeMode="contain" 
                  style={styles.imageLogo} 
                  source={Images.iconoToolbar} 
                />
              </View>
            </>
          ),
        })}
        name="EmpresasScreen"
        component={EmpresasScreen}
      />
      <detalleEmpresaStack.Screen
        options={{ headerShown: false }}
        name="DetalleEmpresaScreen"
        component={DetalleEmpresaScreen}
      />
      <agendamientoStack.Screen
        options={{ headerShown: false }}
        name="AgendamientoScreen"
        component={AgendamientoScreen}
      />
    </homeStack.Navigator>
  );
}

function secondStack() {
  return (
    <misCitasStack.Navigator>
      <misCitasStack.Screen
        options={({navigation}) => ({
          headerShown: false,
          headerTitle: () => (
            <>
              <View style={styles.viewHeader}>
                <Image 
                  resizeMode="contain" 
                  style={styles.imageLogo} 
                  source={Images.iconoToolbar} 
                />
              </View>
            </>
          ),
        })}
        name="MisCitasScreen"
        component={CitasScreen}
      />
      <detalleCitasStack.Screen
        options={({navigation}) => ({
          headerShown: false,
        })}
        name="DetalleCitaScreen"
        component={DetalleCitaScreen}
      />
    </misCitasStack.Navigator>
  );
}

function tabStack() {
  return (
    <tab.Navigator
      screenOptions={({route}) => ({
        tabBarIcon: ({focused}) => {
          let iconName;
          if (route.name === 'Home') {
            iconName = focused
              ? Images.casaActive
              : Images.casa
          } else if (route.name === 'Citas') {
            iconName = focused 
              ? Images.citasActive
              : Images.citas
          }
          return <Image source={iconName} />
        }
      })}
      tabBarOptions={{
        showLabel: false,
      }}>
      <tab.Screen name="Home" component={firstStack} />
      <tab.Screen name="Citas" component={secondStack} />
    </tab.Navigator>
  );
}

function menuStackNavigator() {
  useEffect(() => {
    VersionCheck.needUpdate({forceUpdate: true}).then(async res => {
      if (res.isNeeded) {
        alertNeedUpdate(res.storeUrl, false);
      }
    });
    if(Platform.OS === 'android') {
      NativeModules.SplashScreenModule.hide();
    }
  }, [])
  return (
    <NavigationContainer linking={linking}>
      <stack.Navigator headerMode="none">
        <stack.Screen name="Home" component={tabStack} />
        <stack.Screen name="Error" component={ErrorScreen} />
      </stack.Navigator>
    </NavigationContainer>
  );
};

const styles = StyleSheet.create({
  viewHeader: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  imageLogo: {
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 6,
    marginBottom: 6
  }
});

export default menuStackNavigator;


Get this bounty!!!

#StackBounty: #typescript #npm #yarnpkg #monaco-editor #language-server-protocol editor.IStandaloneCodeEditor' is not assignable to…

Bounty: 100

in order to use monaco in below source code I did install below package but I’m getting that type error. Why is that and how can I fix that?

package:

npm i monaco-editor

I’m using this command:

yarn install

the package file looks like this:

{
  "private": true,
  "name": "node-example",
  "version": "0.13.0",
  "dependencies": {
    "@codingame/monaco-jsonrpc": "^0.3.1",
    "express": "^4.15.2",
    "file-loader": "^4.3.0",
    "monaco-editor": "^0.27.0",
    "monaco-editor-core": "^0.22.3",
    "monaco-editor-webpack-plugin": "^4.1.2",
    "monaco-languageclient": "^0.13.0",
    "normalize-url": "^2.0.1",
    "reconnecting-websocket": "^3.2.2",
    "request-light": "^0.2.2",
    "vscode-json-languageservice": "^4.0.2",
    "vscode-languageserver": "7.0.0",
    "vscode-uri": "^3.0.2",
    "vscode-ws-jsonrpc": "^0.2.0",
    "ws": "^5.0.0"
  },
  "scripts": {
    "prepare": "yarn run clean && yarn run build",
    "compile": "tsc",
    "watch": "tsc -w",
    "clean": "rimraf lib",
    "copy": "cp src/index.html lib/index.html",
    "build": "yarn run compile && webpack && yarn run copy",
    "start": "node lib/server.js",
    "start:ext": "node lib/server.js --external"
  },
  "devDependencies": {
    "webpack-cli": "^4.8.0"
  }
}

And this the error I’m getting:

src/client.ts:32:24 – error TS2345: Argument of type
‘import("path/to/project/monaco-languageclient/example/node_modules/monaco-editor/esm/vs/editor/editor.api").editor.IStandaloneCodeEditor’
is not assignable to parameter of type
‘monaco.editor.IStandaloneCodeEditor’.

this is the full source code:

import { listen, MessageConnection } from 'vscode-ws-jsonrpc';
import {
    MonacoLanguageClient, CloseAction, ErrorAction,
    MonacoServices, createConnection
} from 'monaco-languageclient';
import * as monaco from 'monaco-editor'
import normalizeUrl = require('normalize-url');
const ReconnectingWebSocket = require('reconnecting-websocket');

// register Monaco languages
monaco.languages.register({
    id: 'typescript',
    extensions: ['.ts'],
    aliases: ['TypeScript','ts','TS','Typescript','typescript']
})

// create Monaco editor
const value = `{
    "$schema": "http://json.schemastore.org/coffeelint",
    "line_endings": "unix"
}`;
const editor = monaco.editor.create(document.getElementById("container")!, {
    model: monaco.editor.createModel(value, 'typescript', monaco.Uri.parse('file:///abs/path/to/demo/ts/file.ts')),
    glyphMargin: true,
    theme: "vs-dark",
    lightbulb: {
        enabled: true
    }
});

// install Monaco language client services
MonacoServices.install(editor,{rootUri: "file:///abs/path/to/demo/ts"});

// create the web socket
const url = createUrl('ws://localhost:3000/ts')
const webSocket = createWebSocket(url);
// listen when the web socket is opened
listen({
    webSocket,
    onConnection: connection => {
        // create and start the language client
        const languageClient = createLanguageClient(connection);
        const disposable = languageClient.start();
        connection.onClose(() => disposable.dispose());
    }
});

function createLanguageClient(connection: MessageConnection): MonacoLanguageClient {
    return new MonacoLanguageClient({
        name: "Sample Language Client",
        clientOptions: {
            // use a language id as a document selector
            documentSelector: ['typescript'],
            // disable the default error handler
            errorHandler: {
                error: () => ErrorAction.Continue,
                closed: () => CloseAction.DoNotRestart
            }
        },
        // create a language client connection from the JSON RPC connection on demand
        connectionProvider: {
            get: (errorHandler, closeHandler) => {
                return Promise.resolve(createConnection(connection, errorHandler, closeHandler))
            }
        }
    });
}

function createUrl(path: string): string {
    return normalizeUrl(path);
}

function createWebSocket(url: string): WebSocket {
    const socketOptions = {
        maxReconnectionDelay: 10000,
        minReconnectionDelay: 1000,
        reconnectionDelayGrowFactor: 1.3,
        connectionTimeout: 10000,
        maxRetries: Infinity,
        debug: false
    };
    return new ReconnectingWebSocket(url, [], socketOptions);
}


Get this bounty!!!

#StackBounty: #typescript #redux #react-redux #typescript-typings #.d.ts redux's inferred type in .d.ts doesn't match my VSCode…

Bounty: 50

This is what I have; simple stuff.

interface quote {
  quote: string
  author: string
}

interface StoreState {
  quote: {
    quotes: any[]
  }
}
const mapStateToProps = (state: StoreState) => {
  return {
    quotes: state.quote.quotes,
  }
}

const mapDispatchToProps = (dispatch: Dispatch<AnyAction>) => {   return {
    addQuote: (quote: quote) => dispatch(addQuoteAction(quote)),
    clearQuotes: () => dispatch(clearQuotesAction()),
    deleteQuote: (author: string) => dispatch(deleteQuoteAction(author)),   } }

export default connect(mapStateToProps, mapDispatchToProps)

But the result in d.ts completely forgot about the stuff in mapStateToProps.

enter image description here

This is what my VSCode’s type hint shows (which shows yeah, the type from mapStateToProps (e.g. in this case, quotes: any[]) should be a part of the type param):

enter image description here

I’m using typescript’s .createLanguageService to directly generate the d.ts. Just wondering why the type from mapStateToProps got ignored.

If I write

export default connect(mapStateToProps)

then yup d.ts got the right type from mapStateToProps:

enter image description here

I’m not concerned with the type of connect(mapStateToProps, mapDispatchToProps)(App) but I’m interested to get the correct type for connect(mapStateToProps, mapDispatchToProps).

Also sometimes I do get the right type with mapStateToProps but I’m not consistently getting it.

(could it have something to do with how things are defined in DefinitelyTyped?)


Get this bounty!!!

#StackBounty: #node.js #typescript #webstorm #nvm #ts-node WebStorm + nvm + Typescript + ts-node + Breakpoint Debugging – Randomly Stop…

Bounty: 50

I have an issue with WebStorm that I can’t seem to figure out and JetBrains hasn’t been much help either.

It appears to sometimes show up, sometimes go away, and just flat out make zero sense. Debugging breakpoints in WebStorm will flat out stop working if they’re inside of a non spec file function.

I’m using mocha, and my setup is as follows:

  • nvm – using node 14.16.1
  • mocha 9.02
  • User interface: BDD

Env. Variables:

NODE_ENV=development;TS_NODE_FILES=true;TS_NODE_TRANSPILE_ONLY=true;TS_NODE_PROJECT=tsconfig.tests.json

Extra Mocha Options:

--require ts-node/register

Test file patterns:

src/tests/unit/**/*.ts

JetBrains had thought it was my code base, however, if I were to take and setup my other laptop with it, it breakpoints and works fine. However with WebStorm it randomly stops allowing me to breakpoint debug into nested functions…

I’ve tried uninstalling the nvm node version and reinstalling, wiped out node_modules and reinstalling, tried installing different node version and rebuilding node_modules. Nothing seems to resolve it.

One interesting piece, breakpoints work as expected when I don’t run Spec files and run the app normally.


Get this bounty!!!

#StackBounty: #javascript #node.js #typescript #postgresql #sequelize.js postgres init code with multiple sequelize

Bounty: 100

I am trying to convert js code to ts code (and understanding why something have been done).

This my JS code

use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}


Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Here, there are multiple sequalise

db.sequelize = sequelize;
db.Sequelize = Sequelize;

Can someone please help me in understand meaning, purpose and why both of them exist? and where we would use each of them.

I am able to make sense for sequelize but not for Sequelize. like we already have used new Sequelize( so why would we add it in db object?


Get this bounty!!!