wix-incubator / vscode-glean

The extension provides refactoring tools for your React codebase
MIT License
1.46k stars 56 forks source link

undefined: Duplicate declaration "initLoading" #148

Open endersaka opened 2 years ago

endersaka commented 2 years ago

Microsoft Windows 10 Pro, 10.0.19043 Build 19043 Visual Studio Code 1.62.0 (system setup) glean v5.2.2

I attempted to refactor a class component into a functional component. At the end of the process glean presents an alert displaying the text: undefined: Duplicate declaration "initLoading". You can see it in the following images.

vscode-glean_2021-11-11 114718 vscode-glean_2021-11-11 114634 vscode-glean_2021-11-11 114601 vscode-glean_2021-11-11 114811

The component code (slightly modified from Ant Design documentation example Load More).

import React from 'react';
import { List, Avatar, Button, Skeleton } from 'antd';
import reqwest from 'reqwest';
import 'antd/dist/antd.css';

const count = 20;
const fakeDataUrl = `https://randomuser.me/api/?results=${count}&inc=name,email,picture,login&noinfo`;

class LoadMoreList extends React.Component {
  state = {
    initLoading: true,
    loading: false,
    data: [],
    list: [],
  };

  componentDidMount() {
    this.getData(res => {
      this.setState({
        initLoading: false,
        data: res.results,
        list: res.results,
      });
    });
  }

  getData = callback => {
    reqwest({
      url: fakeDataUrl,
      type: 'json',
      method: 'get',
      contentType: 'application/json',
      success: res => {
        callback(res);
      },
    });
  };

  onLoadMore = () => {
    this.setState({
      loading: true,
      list: this.state.data.concat(
        [...new Array(count)].map(() => ({ loading: true, name: {}, picture: {} })),
      ),
    });
    this.getData(res => {
      const data = this.state.data.concat(res.results);
      this.setState(
        {
          data,
          list: data,
          loading: false,
        },
        () => {
          // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
          // In real scene, you can using public method of react-virtualized:
          // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
          window.dispatchEvent(new Event('resize'));
        },
      );
    });
  };

  render() {
    const { initLoading, loading, list } = this.state;
    const loadMore =
      !initLoading && !loading ? (
        <div
          style={{
            textAlign: 'center',
            marginTop: 12,
            height: 32,
            lineHeight: '32px',
          }}
        >
          <Button onClick={this.onLoadMore}>loading more</Button>
        </div>
      ) : null;

    return (
      <List
        className="demo-loadmore-list"
        loading={initLoading}
        itemLayout="horizontal"
        loadMore={loadMore}
        dataSource={list}
        renderItem={item =>
          console.log(item) || (
            <List.Item
              actions={[<a key="list-loadmore-edit">edit</a>, <a key="list-loadmore-more">more</a>]}
            >
              <Skeleton avatar title={false} loading={item.loading} active>
                <List.Item.Meta
                  avatar={<Avatar src={item.picture.large} />}
                  title={item.name.title + ' ' + item.name.first + ' ' + item.name.last}
                  description={item.login.username}
                />
                <div>content</div>
              </Skeleton>
            </List.Item>
          )
        }
      />
    );
  }
}

export default LoadMoreList;
tangweizhi commented 2 years ago

me too! how to fix

ankitprahladsoni commented 2 years ago

instead of destructure statement here const { initLoading, loading, list } = this.state;, access all variables directly from this.state everywhere. The extension will work after this

endersaka commented 2 years ago

instead of destructure statement here const { initLoading, loading, list } = this.state;, access all variables directly from this.state everywhere. The extension will work after this

Thanks. I'll try it.

mtchuenten commented 1 year ago

Hello all,

Thanks @ankitprahladsoni, I'm also trying to convert a react class component into a functional component and using your approach effectively eliminates that error message. Now I get a different error message I have no clue how to fix: You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a Identifier node without passing scope and parentPath.

Please find below the class I'm trying to transform:

import React from 'react';

import DataGrid, {
  Column,
  Selection,
  Toolbar,
  Item,
} from 'devextreme-react/data-grid';
import SelectBox from 'devextreme-react/select-box';
import Button from 'devextreme-react/button';
import { employees } from './data.js';

const titles = ['All', 'Dr.', 'Mr.', 'Mrs.', 'Ms.'];

class App extends React.Component {
  constructor(props) {
    super(props);

    this.dataGrid = null;
    this.selectionChangedBySelectBox = false;

    this.state = {
      prefix: '',
      selectedEmployeeNames: 'Nobody has been selected',
      selectedRowKeys: [],
    };

    this.onClearButtonClicked = this.onClearButtonClicked.bind(this);
    this.onSelectionChanged = this.onSelectionChanged.bind(this);
    this.onSelectionFilterChanged = this.onSelectionFilterChanged.bind(this);
  }

  render() {
    // commented out the below to avoid the undefined: Duplicate declaration error
    // const {
    //    prefix, selectedRowKeys, selectedEmployeeNames,
    //  } = this.state;

    return (
      <div>
        <DataGrid
          id="grid-container"
          dataSource={employees}
          keyExpr="ID"
          onSelectionChanged={this.onSelectionChanged}
          ref={(ref) => { this.dataGrid = ref; }}
          selectedRowKeys={this.state.selectedRowKeys}
          showBorders={true}
        >
          <Selection mode="multiple" />
          <Column dataField="Prefix" caption="Title" width={70} />
          <Column dataField="FirstName" />
          <Column dataField="LastName" />
          <Column dataField="Position" width={180} />
          <Column dataField="BirthDate" dataType="date" width={125} />
          <Column dataField="HireDate" dataType="date" width={125} />
          <Toolbar>
            <Item location="before">
              <SelectBox
                dataSource={titles}
                onValueChanged={this.onSelectionFilterChanged}
                placeholder="Select title"
                width={150}
                value={this.state.prefix}
              />
            </Item>
            <Item location="before">
              <Button
                disabled={!this.state.selectedRowKeys.length}
                onClick={this.onClearButtonClicked}
                text="Clear Selection"
              />
            </Item>
          </Toolbar>
        </DataGrid>
        <div className="selected-data">
          <span className="caption">Selected Records:</span>{' '}
          <span>
            { this.state.selectedEmployeeNames }
          </span>
        </div>
      </div>
    );
  }

  onSelectionChanged({ selectedRowKeys, selectedRowsData }) {
    this.selectionChangedBySelectBox = false;

    this.setState({
      prefix: null,
      selectedEmployeeNames: getEmployeeNames(selectedRowsData),
      selectedRowKeys,
    });
  }

  onClearButtonClicked() {
    this.dataGrid.instance.clearSelection();
  }

  onSelectionFilterChanged({ value }) {
    this.selectionChangedBySelectBox = true;

    const prefix = value;

    if (prefix) {
      const filteredEmployees = prefix === 'All' ? employees : employees.filter((employee) => employee.Prefix === prefix);
      const selectedRowKeys = filteredEmployees.map((employee) => employee.ID);

      this.setState({
        prefix,
        selectedRowKeys,
        selectedEmployeeNames: getEmployeeNames(filteredEmployees),
      });
    }
  }
}

function getEmployeeName(row) {
  return `${row.FirstName} ${row.LastName}`;
}

function getEmployeeNames(selectedRowsData) {
  return selectedRowsData.length ? selectedRowsData.map(getEmployeeName).join(', ') : 'Nobody has been selected';
}

export default App;

And the data.js file is as below:

export const employees = [{
  ID: 1,
  FirstName: 'John',
  LastName: 'Heart',
  Prefix: 'Mr.',
  Position: 'CEO',
  Picture: 'images/employees/01.png',
  BirthDate: '1964/03/16',
  HireDate: '1995/01/15',
  Notes: 'John has been in the Audio/Video industry since 1990. He has led DevAv as its CEO since 2003.\r\n\r\nWhen not working hard as the CEO, John loves to golf and bowl. He once bowled a perfect game of 300.',
  Address: '351 S Hill St.',
}, {
  ID: 20,
  FirstName: 'Olivia',
  LastName: 'Peyton',
  Prefix: 'Mrs.',
  Position: 'Sales Assistant',
  Picture: 'images/employees/09.png',
  BirthDate: '1981/06/03',
  HireDate: '2012/05/14',
  Notes: 'Olivia loves to sell. She has been selling DevAV products since 2012. \r\n\r\nOlivia was homecoming queen in high school. She is expecting her first child in 6 months. Good Luck Olivia.',
  Address: '807 W Paseo Del Mar',
}, {
  ID: 4,
  FirstName: 'Robert',
  LastName: 'Reagan',
  Prefix: 'Mr.',
  Position: 'CMO',
  Picture: 'images/employees/03.png',
  BirthDate: '1974/09/07',
  HireDate: '2002/11/08',
  Notes: 'Robert was recently voted the CMO of the year by CMO Magazine. He is a proud member of the DevAV Management Team.\r\n\r\nRobert is a championship BBQ chef, so when you get the chance ask him for his secret recipe.',
  Address: '4 Westmoreland Pl.',
}, {
  ID: 5,
  FirstName: 'Greta',
  LastName: 'Sims',
  Prefix: 'Ms.',
  Position: 'HR Manager',
  Picture: 'images/employees/04.png',
  BirthDate: '1977/11/22',
  HireDate: '1998/04/23',
  Notes: 'Greta has been DevAV\'s HR Manager since 2003. She joined DevAV from Sonee Corp.\r\n\r\nGreta is currently training for the NYC marathon. Her best marathon time is 4 hours. Go Greta.',
  Address: '1700 S Grandview Dr.',
}, {
  ID: 6,
  FirstName: 'Brett',
  LastName: 'Wade',
  Prefix: 'Mr.',
  Position: 'IT Manager',
  Picture: 'images/employees/05.png',
  BirthDate: '1968/12/01',
  HireDate: '2009/03/06',
  Notes: 'Brett came to DevAv from Microsoft and has led our IT department since 2012.\r\n\r\nWhen he is not working hard for DevAV, he coaches Little League (he was a high school pitcher).',
  Address: '1120 Old Mill Rd.',
}, {
  ID: 7,
  FirstName: 'Sandra',
  LastName: 'Johnson',
  Prefix: 'Mrs.',
  Position: 'Controller',
  Picture: 'images/employees/06.png',
  BirthDate: '1974/11/15',
  HireDate: '2005/05/11',
  Notes: 'Sandra is a CPA and has been our controller since 2008. She loves to interact with staff so if you\'ve not met her, be certain to say hi.\r\n\r\nSandra has 2 daughters both of whom are accomplished gymnasts.',
  Address: '4600 N Virginia Rd.',
}, {
  ID: 10,
  FirstName: 'Kevin',
  LastName: 'Carter',
  Prefix: 'Mr.',
  Position: 'Shipping Manager',
  Picture: 'images/employees/07.png',
  BirthDate: '1978/01/09',
  HireDate: '2009/08/11',
  Notes: 'Kevin is our hard-working shipping manager and has been helping that department work like clockwork for 18 months.\r\n\r\nWhen not in the office, he is usually on the basketball court playing pick-up games.',
  Address: '424 N Main St.',
}, {
  ID: 11,
  FirstName: 'Cynthia',
  LastName: 'Stanwick',
  Prefix: 'Ms.',
  Position: 'HR Assistant',
  Picture: 'images/employees/08.png',
  BirthDate: '1985/06/05',
  HireDate: '2008/03/24',
  Notes: 'Cindy joined us in 2008 and has been in the HR department for 2 years. \r\n\r\nShe was recently awarded employee of the month. Way to go Cindy!',
  Address: '2211 Bonita Dr.',
}, {
  ID: 30,
  FirstName: 'Kent',
  LastName: 'Samuelson',
  Prefix: 'Dr.',
  Position: 'Ombudsman',
  Picture: 'images/employees/02.png',
  BirthDate: '1972/09/11',
  HireDate: '2009/04/22',
  Notes: 'As our ombudsman, Kent is on the front-lines solving customer problems and helping our partners address issues out in the field.    He is a classically trained musician and is a member of the Chamber Orchestra.',
  Address: '12100 Mora Dr',
}, {
  ID: 21,
  FirstName: 'Taylor',
  LastName: 'Riley',
  Prefix: 'Mr.',
  Position: 'Network Admin',
  Picture: '',
  BirthDate: '1982/08/14',
  HireDate: '2012/04/14',
  Notes: 'If you are like the rest of us at DevAV, then you\'ve probably reached out for help from Taylor. He does a great job as a member of our IT department.',
  Address: '7776 Torreyson Dr',
}];

Regards.

ankitprahladsoni commented 1 year ago

@mtchuenten I just tried moving the render method to the bottom and it worked.

import React, { useState, useRef, useCallback } from 'react';

import DataGrid, { Column, Selection, Toolbar, Item } from 'devextreme-react/data-grid';
import SelectBox from 'devextreme-react/select-box';
import Button from 'devextreme-react/button';
import { employees } from './data.js';

const titles = ['All', 'Dr.', 'Mr.', 'Mrs.', 'Ms.'];

const App = (props) => {
    const [prefix, setPrefix] = useState();
    const [selectedEmployeeNames, setSelectedEmployeeNames] = useState();
    const [selectedRowKeys, setSelectedRowKeys] = useState();
    const selectionChangedBySelectBox = useRef();
    const dataGrid = useRef();
    const onSelectionChanged = useCallback(() => {
        selectionChangedBySelectBox.current = false;
        setPrefix(null);
        setSelectedEmployeeNames(getEmployeeNames(selectedRowsData));
        setSelectedRowKeys(selectedRowKeys);
    });
    const onClearButtonClicked = useCallback(() => {
        props.instance.clearSelection();
    });
    const onSelectionFilterChanged = useCallback(() => {
        selectionChangedBySelectBox.current = true;
        const prefix = value;

        if (prefix) {
            const filteredEmployees =
                prefix === 'All'
                    ? employees
                    : employees.filter((employee) => employee.Prefix === prefix);
            const selectedRowKeys = filteredEmployees.map((employee) => employee.ID);
            setPrefix(prefix);
            setSelectedRowKeys(selectedRowKeys);
            setSelectedEmployeeNames(getEmployeeNames(filteredEmployees));
        }
    });
    // commented out the below to avoid the undefined: Duplicate declaration error
    // const {
    //    prefix, selectedRowKeys, selectedEmployeeNames,
    //  } = this.state;
    return (
        <div>
            <DataGrid
                id="grid-container"
                dataSource={employees}
                keyExpr="ID"
                onSelectionChanged={onSelectionChanged}
                ref={(ref) => {
                    dataGrid.current = ref;
                }}
                selectedRowKeys={selectedRowKeys}
                showBorders
            >
                <Selection mode="multiple" />
                <Column dataField="Prefix" caption="Title" width={70} />
                <Column dataField="FirstName" />
                <Column dataField="LastName" />
                <Column dataField="Position" width={180} />
                <Column dataField="BirthDate" dataType="date" width={125} />
                <Column dataField="HireDate" dataType="date" width={125} />
                <Toolbar>
                    <Item location="before">
                        <SelectBox
                            dataSource={titles}
                            onValueChanged={onSelectionFilterChanged}
                            placeholder="Select title"
                            width={150}
                            value={prefix}
                        />
                    </Item>
                    <Item location="before">
                        <Button
                            disabled={!selectedRowKeys.length}
                            onClick={onClearButtonClicked}
                            text="Clear Selection"
                        />
                    </Item>
                </Toolbar>
            </DataGrid>
            <div className="selected-data">
                <span className="caption">Selected Records:</span>{' '}
                <span>{selectedEmployeeNames}</span>
            </div>
        </div>
    );
};

function getEmployeeName(row) {
    return `${row.FirstName} ${row.LastName}`;
}

function getEmployeeNames(selectedRowsData) {
    return selectedRowsData.length
        ? selectedRowsData.map(getEmployeeName).join(', ')
        : 'Nobody has been selected';
}

export default App;
mtchuenten commented 1 year ago

Thank you for pointing that out @ankitprahladsoni, it alllowed me to make some progress.

I also moved the render method to the bottom of the class definition and glean could convert the class component into a functional component, but with an error, such that I'm not sure if the conversion process actually completed:

Cannot read properties of undefined (reading 'tsAction')

The component isn't rendered because react encountered an error during compilation:

Line 24:47: 'selectedRowsData' is not defined no-undef Line 32:20: 'value' is not defined no-undef

I don't know if this error is related to the error reported by glean during component conversion.

Please note that I use glean v5.2.2 and react v18.2.0, if that can be of any relevance.

Regards.

ankitprahladsoni commented 1 year ago

I've noticed it before and am unsure if it's a bug, but when functions are converted to useCallback, they lose the arguments. All you have to do now is to update the newly created useCallback with the params from the original file.