Home > Back-end >  In react class based component this.setsate is used but state is not defined in constructor if I hav
In react class based component this.setsate is used but state is not defined in constructor if I hav

Time:05-07

class Dashboard extends Component {
  constructor(props) {
    super(props)
    this.state = {
      assetList: [],
      assetList1: [];
    }
  }
  componentDidMount = async () => {
    const web3 = window.web3
    const LandData=Land.networks[networkId]
    if (LandData) {
      const landList = new web3.eth.Contract(Land.abi, LandData.address)
      this.setState({ landList })
    }
  }

  ...
}

In this code the state for landlist is not defines in constructor but setState is used. If I have to convert the code to a function component, what will be the equivalent code?

CodePudding user response:

In React class components, there existed a single state object and you could update it with any properties you needed. State in React function components functions a little differently.

React function components use the useState hook to explicitly declare a state variable and updater function.

You can use a single state, and in this case the functionality would be pretty similar, keeping in mind though that unlike the this.setState of class components, the useState

Example:

const Dashboard = () => {
  const [state, setState] = React.useState({
    assetList: [],
    assetList1: []
  });

  useEffect(() => {
    const web3 = window.web3;
    const LandData = Land.networks[networkId];
    if (LandData) {
      const landList = new web3.eth.Contract(Land.abi, LandData.address);
      setState(prevState => ({
        ...prevState,
        landList,
      }));
    }
  }, []);

  return (
    ...
  );
};

With the useState hook, however, you aren't limited to a single state object, you can declare as many state variables necessary for your code to function properly. In fact it is recommended to split your state out into the discrete chunks of related state.

Example:

const Dashboard = () => {
  const [assetLists, setAssetLists] = React.useState({
    assetList: [],
    assetList1: []
  });
  const [landList, setLandList] = React.useState([]);

  useEffect(() => {
    const web3 = window.web3;
    const LandData = Land.networks[networkId];
    if (LandData) {
      const landList = new web3.eth.Contract(Land.abi, LandData.address);
      setLandList(landList);
    }
  }, []);

  return (
    ...
  );
};

CodePudding user response:

const Dashboard = () => {
    const [assetList, setAssetList] = useState([])
    const [assetList1, setAssetList1] = useState([])

    useEffect(() => {
        const web3 = window.web3
        const LandData = Land.networks[networkId]
        if (LandData) {
            const landList = new web3.eth.Contract(Land.abi, LandData.address)
            setAssetList(landList)
        }
    }, [])
  • Related