'this' is undefined in react for adding checkbox events

I encountered error in react wherein this is undefined. This is my first time developing a react application.

In UI, it says Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined while in console the value of this is undefined.

Thank you for your help.

Here is the existing code:

import React, { useState, useEffect, useRef } from "react";
//import makeData from "../makeData";
import { useTableState } from "react-table";

import { Button } from "../Styles";
import Table from "../TransactionPanelTable";

// Simulate a server
const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

  // Ideally, you would pass this info to the server, but we'll do it here for convenience
  const filtersArr = Object.entries(filters);

  // Get our base data
  let rows = [];

  for (let i = 0; i < 1000; i++) {
    rows.push({
      transaction_seq: 1234,
      rec_count: 1234,
      user_id: "test",
      updated_at: "",
      duration: 1.23
    });
  }

  // Apply Filters
  if (filtersArr.length) {
    rows = rows.filter(row =>
      filtersArr.every(([key, value]) => row[key].includes(value))
    );
  }

  // Apply Sorting
  if (sortBy.length) {
    const [{ id, desc }] = sortBy;
    rows = [...rows].sort(
      (a, b) => (a[id] > b[id] ? 1 : a[id] === b[id] ? 0 : -1) * (desc ? -1 : 1)
    );
  }

  // Get page counts
  const pageCount = Math.ceil(rows.length / pageSize);
  const rowStart = pageSize * pageIndex;
  const rowEnd = rowStart + pageSize;

  // Get the current page
  rows = rows.slice(rowStart, rowEnd);

  let checkedMap = new Map();
  rows.forEach(row => checkedMap.set(row, false)); //preset each to false, ideally w/ a key instead of the entire row
  this.setState({ checkedMap: checkedMap });

  //handleCheckedChange(row) {
  //  let modifiedMap = this.state.checkedMap;
  //  modifiedMap.set(row, !this.state.checkedMap.get(row));
  //  this.setState({ checkedMap: modifiedMap });
  //}

  return {
    rows,
    pageCount
  };
};

'this' is undefined because you haven't bounded the context of the component to the method. As you are new to react, i would suggest you to go through concepts like bind,es6 and other js lingos so that you can code better and avoid such errors.

In this case you need to bind the context either by using bind method or by using es6 arrow functions which are class functions.

Add below code in constructor function where you are calling this getServerData function.

getServerData = getServerData.bind(this);

Here bind will return new method which will set context (this) to your calling class.

It is preferable to set state in class with in that promise resolved function.

this.getServerData = this.getServerData.bind(this);

Comments
  • Welcome to SO. We are here to help other users when they experience problems to point them in the right direction. We are not here to fix your bugs are write new code for you. Try to google why you get a Type Error. What did you try to fix your problem?