Material React Table simple filtering not working Cannot read properties of null (reading ‘value’)

Hello we’ve been using Material React Table npm package for showing data, but filtering isn’t working, so every time I type a letter this error pops out

Uncaught TypeError: Cannot read properties of null (reading ‘value’)
at MRT_FilterTextField.tsx:119:1
at later (debounce.js:7:1)

This is the code

const columns = useMemo(
    () => [
      {
        header: `${t("login_title_email")}`,
        accessorFn: (row) => row.log_email_address,
        enableClickToCopy: true,
        filterVariant: "text", // default
      },
      {
        header: `${t("login_title_ip")}`,
        accessorKey: "login_attempt_ip",
        enableClickToCopy: true,
      },
      {
        header: `${t("login_title_date")}`,
        accessorFn: (row) => new Date(row.log_date),
        filterFn: "greaterThanOrEqualTo",
        sortingFn: "datetime",
        id: "log_date",
        Cell: ({ cell }) => cell.getValue()?.toLocaleDateString(),
        Filter: ({ column }) => (
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <DatePicker
              onChange={(newValue) => {
                column.setFilterValue(newValue);
              }}
              slotProps={{
                textField: {
                  sx: { minWidth: "120px" },
                  variant: "standard",
                },
              }}
              value={column.getFilterValue()}
            />
          </LocalizationProvider>
        ),
      },
      {
        header: `${t("login_type")}`,
        accessorKey: "log_type",
      },
    ],
    []
  );
 <MaterialTable
            data={logs}
            columns={columns}
            enableColumnOrdering
            enableGrouping
            enablePinning
            enableRowNumbers
            initialState={{
              density: "compact",
              showGlobalFilter: true,
              showColumnFilters: true,
            }}
          />

Data structure is like this:

const data = [
{log_date: "2023-06-02T04:01:43.665Z"
log_email_address: "[email protected]"
log_type: "login_email"
login_attempt_ip: 
"10.10.16.10"
user_id: "12334444"}
]

I would appreciate any kind of help to solve the issue 😀
Thank you

Javascript addEventlistener for ‘change’ event is not working on input

Javascript addEventlistener for ‘change’ event is not working on input.

I have series of inputs in a form, selected them using querySelectorAll, added event listener to each input using forEach loop. The goal is to get the value inside the input on change, so I can run my validation functions. This works fine on events like ‘keyup’ but according to docs ‘change’ event should also produce same result. Which it doesn’t in my case. Or is change event is just limited to select tag in html.

const inputs = document.querySelectorAll('.input');

inputs.forEach(input => {
  input.addEventListener('change', function (e) {
    console.log(e.target.value);
  });
});

What is the equivalent of add.classList in React for toggling visibility?

Adding and removing classes to elements in React

I’m a complete newb with React but basically I’ve been trying to make it so that a container goes from hidden to visible when you click a button.
Usually I’d just do an eventListner and add.classList or remove.classList but I can’t find the equivalent to that in react ?
I’ve tried figuring it out with useState and everything but I feel like I’m just overlooking something simple.
I would really appreciate some help it’s been like hours and my tiny brain is gonna explode

Cannot read properties of undefined (reading ‘response’) error is raised when reading fixture file data in cypress

Actually I have searched many times, but I couldn’t find the solution. I have tried to read from fixture file users’ data, the first entity will be read successfully, but when trying to read the other data in the fixture file, the error message “Cannot read properties of undefined (reading ‘response’)” is raised.

Code:

js file (test case file)

it("ValidateOnMsgAfterLogin", function(){ 

 
    
cy.fixture("UserCredential").then((usersBundle)=>{
  
    usersBundle.forEach((userBundle)=>{
    cy.visit("https://opensource-demo.orangehrmlive.com");
    cy.wait(6000);
// action

cy.get('[name="username"]').type(userBundle.username);

cy.get('[type="password"]').type(userBundle.password);
cy.get(".oxd-button.oxd-button--medium.oxd-button--main.orangehrm-login-button").click();




    if(userBundle.username=="Admin" && userBundle.password=="admin123"){
        cy.get(".oxd-text.oxd-text--h6.oxd-topbar-header-breadcrumb-module").as("Msg");
       cy.get("@Msg").should("have.text", "Dashboard");

         // cy.get(".oxd-userdropdown-tab").click(); // span
         cy.get(".oxd-userdropdown-img").click();
          cy.get("a").contains("Logout").click();
       
    }

    else{
cy.get(".oxd-text oxd-text--p.oxd-alert-content-text").contains("Invalid credentials").should("equal", userBundle.message);
    }



});

});




});

fixture file

[
    {
        "username": "Admin",
        "password": "admin123",
        "message": "PIM"
      
    },

    {
        "username": "Admin1",
        "password": "admin12",
        "message": "PIM"
        
    },

    {
        "username": "Admin3",
        "password": "admin123",
        "message": "PIM"
    
    }


]

JavaScript cannot inject icon into Google Docs

Hi I am making a chrome extension and am trying to inject and icon:

const imageElement = document.createElement("img");
imageElement.src = "./assets/play.png";
imageElement.alt = "Clickable Image";
imageElement.style.width = "50px";
imageElement.style.height = "50px";
imageElement.style.cursor = "pointer";
imageElement.style.left = "0px";
imageElement.style.top = "0px";

onto the Google Docs page. Not on the page where you type but just anywhere on the page. I can do this on any other page like so:

document.body.appendChild(imageElement);

Why doesn’t this work on Google Docs?

Weird looping over bug in nunjucks

I have built a server in nodejs for a multiplayer snake game.

I am currently working on allowing users to create their own bots, and for this I must have a way to generate and store API keys.

I have this figured out. Here is a nice screenshot from AWS DynamoDB showing how the data is formatted.

item schema

The item we want to focus on is the api_keys row. Expanded, it is just a list of API keys [<key>,<key>,etc]
Each api key is just a string that I generate with a helper function.

  function generateAPIKey() {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let apiKey = '';
  
    for (let i = 0; i < 32; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      apiKey += characters.charAt(randomIndex);
    }
  
    return apiKey;
  }

This all works fine. I then created a login and signup system-> this works fine too!

The problem came up when I tried to make a table of all the API keys for a dashboard. Here is how the dashboard is supposed to look.

enter image description here

Here is how I managed this one.

{% set api_keys =  ["45ZeHLkHLskSbRuBvLObUGZ3lfDSJTVZ","8DAefL5BtSwVOUAp0d1ZYrEEr0sliGBU","9XZLnqBwARSMEFv4O4PBtcxY4Lpob3x2","BKce7wVSnblYEfWv2pAXHlbyrCuPpxmn","BrCv6cHP6uFaohS11GnWIllvzB3VoX4K","CJlyot3evxeR6fgW98sTBblKmrzKaRYy","CsCvTrJrdscXqYoLHnoRBlLwpReNKEJT","IYaitmquR42MafZlpd6clsY9e8NMCcmL","LU06037xiU71ZZJcfgXCauvlTuGybM6N","MZU0aVmyCMcsc2qaVsk9OUXGBixy9zxQ","PapmjncSJYDcUtTaDuatgZwXyIwubiQ2","RH0GV1SqX1IUAL0Rx9MQrlaK3BrK61Mr","RJ3VkuYbp0Zxz2lwQdRGwyKmtpH1JyMY","RMUKYDi0lm0AmQIadaZRx3J6pNWlJ5k9","RvnLoV7vtgEBEhvsLDMVJKXFugcoXHoY","i9LtNKURTBV5R3JGZNnjWfhq0kJz8TgF","ju0ssxnrH3ZoBxhtKwtuFJuWpNAJzSo0","mWBWiIfdA6C3KRCMquGJC76u7WMTPPdE","nyhHKOqT2G2zX95I99MHXKzJLchYsqZb","o0seZ0nYXH021Cy5vTVtthaUqY9whwOp","x5Sj0pFYrK4CDoXAWIrZqhoCTUur3AXo"]  %}

This is just filling the api_keys variable with randomly generated api keys.

Then, I fill the rows with the following lines

{% for uid in api_keys %}
<tr class = "table-row" id="row-{{ loop.index0 }}">
   <td><b>{{ loop.index0 }}</b></td>
   <td class = "uid">{{ uid }}</td>
   <td class = "manage">
      <button class = "btn btn-inline">Copy Key</button>
      <button class = "btn btn-danger btn-inline">Delete</button>
   </td>
</tr>
{% endfor %}

and this works too!

The problem arises when I try to loop over the user data. If I switch from doing {% for uid in api_keys %} to {% for uid in user.api_keys %}, everything breaks.

No errors in the console, nothing on the server, but the rows dont print out. I just get an empty table.

I assumed that the error was that user.api_keys was an empty array, or something like that. So, I printed the variable just to check.

{{ user.api_keys | dump }}

enter image description here

Logs everything correctly!
The loop just doesnt work when I use the user data instead of template data.

for reference, here is the full code on github

If anyone has the foggiest idea please help me out here. Everything looks correct, it just doesnt work!

Edit

I have been doing some more testing, and I found that just trying to log 1 element from the list (instead of using dump) returns nothing as well.

{{ user.api_keys[0] }}

is just empty, while

{{ api_keys[0 }} /* the pre filled template one */

displays the key properly

Javascript: function scope is different to function assigned as variable [duplicate]

I’ve got a function:

export default class Popup {
  shower(label, value, valueList, saveEvent) {
    let classInstance = this;
    let domObjects = [ classInstance.dom.text(label, "p") ];
  }
}

Which is called like this:

export default class Controller {
  constructor(model, view) {
    this.model = model;
    this.view = view;
  }

function fred(void){
    fn=this.view.popup.shower;
    fn(label, stat.value, lst, myOtherfn); 

}

..But that doesn’t work. If fails because, when called that way, there is something undefined about

classInstance.dom.text(label, "p") 

(when called from the exact same place as a normal call, it works correctly)

function fred(void){
    this.view.popup.shower(label, stat.value, lst, myOtherfn); 
}

I don’t know enough about javascript even to be dangerous. What does dom.text(“mytext”
, “p”)
mean? Apparently I get a different this.dom from the two call methods? And how can I use a variable procedure in a way that doesn’t mess with scope?

Hide parent element not containing specific text

I am trying to hide parent elements using ID of child as selector; if they do not contain specific text. In this case *. Must be this way and have to use jQuery.

So far I have this:

HTML

<div>
    <label>
        First name <font color="red">*</font>
        <input type="text" id="guest_first_name">
    </label>
</div>

</br>

<div>
    <label>
        Last name 
        <input type="text" id="guest_last_name">
    </label>
</div>

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<script>
 $(document).ready(function() {

    let checkthis = $("#guest_first_name, #guest_last_name").parent();  
    var removewithout = "*";
    checkthis.not(removewithout).hide();

 })

</script>

Struggling to check elements that do not contain text and then hide. Trying to hide <label> with text Last name as it does not contain *. Hope this is clear. Any help is appreciated.

Thanks

Incorrect Date Range and Skipping Data in Search Functionality

Ag-grid+tadabase,javascript, pipe data pull, and trying to enhance our ability to date range search more efficiently.

I have implemented a search functionality in my web application, where users can input various search parameters including date range. The search works well for other inputs, but I’m facing issues with the date search input.

The problem is that when I input a date in the search field, the search results always start from the day after the inputted date, and im aware its because of the is after but no matter what i try it doesnt seem to work in another way. Additionally, when I input a large date range, the search skips some of the data instead of providing all the available data within the range.

Here is an overview of how the date search is intended to work:

The “Load In” date is represented by field_41.
The “Pick Up” date is represented by field_43.
If only one date is inputted, the search should display the data for that day and the next 90 days.
If a date range is provided, the search should return all the data within that range.
I suspect there might be an issue with how I’m handling the date inputs or how I’m comparing the dates in the search query.

I would appreciate any guidance or suggestions on how to fix this issue and make the date search function correctly. Thank you!

var columnConfig = {
  'Job Number': { field: 'field_36', width: 130 },
  'Description': { field: 'field_37', width: 200 },
  'Status': { field: 'field_178', width: 95 },
  'Client': { field: 'field_46', width: 150 },
  'Account Manager': { field: 'field_185', width: 170 },
  'Project Manager': { field: 'field_39', width: 170 },
  'Site': { field: 'field_169_val', width: 125 },
  'Type': { field: 'field_40', width: 100 },
  'Load In': { field: 'field_41', width: 150 },
  'Pick Up': { field: 'field_43', width: 150 },
  'Revenue': {
    field: 'field_771',
    aggFunc: 'sum',
    width: 150,
    valueFormatter: function(params) {
      // Custom value formatter for the 'Revenue' column
      var rawValue = params.value;
      if (typeof rawValue === 'number') {
        // Format the value as currency with dollar sign and comma separators
        var formattedValue = '$' + rawValue.toLocaleString('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        });
        return formattedValue;
      } else {
        return rawValue;
      }
    },
    enableRowGroup: true,
    rowGroupIndex: 0,
    pivotValueColumn: 'field_771',
    pivotTotalColumnIds: ['field_771'],
  },
};
// Create column definitions based on the column configuration
var columnDefs = Object.keys(columnConfig).map(function(headerName) {
  var colDef = columnConfig[headerName];
  var definition = {
    headerName: headerName,
    field: colDef.field,
    resizable: true,
    width: colDef.width || null,
    valueFormatter: colDef.valueFormatter || null,
  };
  if (colDef.aggFunc) {
    definition.aggFunc = colDef.aggFunc;
  }
  if (colDef.valueParser) {
    definition.valueParser = colDef.valueParser;
  }
  return definition;
});

var eGridDiv = document.querySelector('#myGrid');

// Select elements from the DOM
var searchButton = document.querySelector('#searchButton');
var searchForm = document.querySelector('#yourFormId');

eGridDiv.style.display = 'none'; // Hide the grid initially

// Add event listener to the search button
searchButton.addEventListener('click', function(e) {
  e.preventDefault();
  var inputs = Array.from(searchForm.elements).filter(function(element) {
    // Collect input values from the search form
    return element.tagName === 'INPUT';
  });
  if (!checkInputs(inputs)) {
    return;
  }
  var jobNumber = document.querySelector('#jobNumber').value.trim();
  var description = document.querySelector('#description').value.trim();
  var client = document.querySelector('#client').value.trim();
  var accountManager = document.querySelector('#accountManager').value.trim();
  var projectManager = document.querySelector('#projectManager').value.trim();
  var site = document.querySelector('#site').value.trim();
  var type = document.querySelector('#type').value.trim();
  var dateStart = document.querySelector('#dateStart').value.trim();
  var dateEnd = document.querySelector('#dateEnd').value.trim();

  eGridDiv.style.display = ''; // Show the grid
  performSearch(jobNumber, description, client, accountManager, projectManager, site, type, dateStart, dateEnd); // Perform the search with the input values
});

// Configure the grid options
var gridOptions = {
  columnDefs: columnDefs,
  defaultColDef: {
    sortable: true,
    filter: true,
    resizable: true,
    autoSize: true,
    groupable: true,
    enablePivot: true,
    suppressMenuHide: true,
    suppressMovable: false,
    enableRowGroup: true,
    groupSuppressAutoColumn: false,
    rowSelection: 'multiple',
  },
  rowGroupPanelShow: 'onlyWhenGrouping',
  multiSortKey: 'ctrl',
  groupDefaultExpanded: 0,
  groupIncludeTotalFooter: true,
  rowData: null,
  aggregationColumns: ['field_771'],
  pagination: false,
  paginationPageSize: 25,
  sideBar: true,
  defaultToolPanel: 'columns',
  groupUseEntireRow: false,
  groupIncludeFooter: true,
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Group',
    minWidth: 200,
    cellRendererParams: {
      checkbox: false,
      innerRenderer: 'agGroupCellRenderer',
      footerValueGetter: 'function(params) { return params.api ? params.api.getValue("field_771", "sum") : 0; }',
      cellRendererParams: {},
    },
  },
  enableRangeSelection: true,
  enableCellTextSelection: true,
  enableBrowserTooltips: true,
  onColumnRowGroupChanged: function(params) {
    var groupedCols = params.columnApi.getRowGroupColumns();
    if (groupedCols.length > 0) {
      var headerName = groupedCols[0].colDef.headerName;
      params.api.refreshHeader();
    }
  },
};
// Set up the grid using ag-Grid library
new agGrid.Grid(eGridDiv, gridOptions);
// Function to perform the search
function performSearch(jobNumber, description, client, accountManager, projectManager, site, type, dateStart, dateEnd) {
  var today = new Date();
  var defaultDate = today.toISOString().split('T')[0];
  var futureDate = new Date();
  futureDate.setDate(today.getDate() + 90);
  var defaultEndDate = futureDate.toISOString().split('T')[0];
  var pageNumber = 0;
  var loadInDateStart = dateStart !== '' ? new Date(dateStart) : new Date(defaultDate);
  loadInDateStart.setUTCHours(0, 0, 0, 0); // Sets the time to 00:00:00
  
  var pickUpDateStart;
  if (dateEnd !== '') {
    pickUpDateStart = new Date(dateEnd);
    pickUpDateStart.setUTCHours(23, 59, 59, 999); // Sets the time to 23:59:59
  } else {
    pickUpDateStart = new Date(defaultEndDate);
    pickUpDateStart.setUTCHours(23, 59, 59, 999); // Sets the time to 23:59:59
  }

  // Format the pickUpDateStart to match the expected format
  var formattedPickUpDateStart = pickUpDateStart.toISOString().split('T')[0];
  var searchQuery = {
    field_36: jobNumber || undefined,
    field_37: description || undefined,
    field_46: client || undefined,
    field_185: accountManager || undefined,
    field_39: projectManager || undefined,
    field_169_val: site || undefined,
    field_40: type || undefined,
    field_178: 'OPEN',
    field_771: { '$sum': 1 },
  };

 // Date comparisons
 if (loadInDateStart && pickUpDateStart) {
    searchQuery['field_41'] = { '$gte': loadInDateStart.toISOString(), '$lte': pickUpDateStart.toISOString() };
  } else if (loadInDateStart) {
    searchQuery['field_41'] = { '$gte': loadInDateStart.toISOString() };
  } else if (pickUpDateStart) {
    searchQuery['field_41'] = { '$lte': pickUpDateStart.toISOString() };
  }

  // Perform the search using TB.triggerPipe() function
  TB.triggerPipe(
    'removed for privacy',
    {
      tableId: 'lGArg7rmR6',
      condition: 'AND',
      page: pageNumber || '',
      pageSize: 5000,
      fieldList: 'field_36,field_37,field_178,field_41,field_46,field_185,field_39,field_169,field_40,field_43,field_771',
      sortByField: '',sortOrder: '',
      field_id_0: 'field_36',field_op_0: '',field_val_0: 
      jobNumber,field_id_1: 'field_37',field_op_1: '',field_val_1: description,
      field_id_2: 'field_46',field_op_2: '',field_val_2: client,
      field_id_3: 'field_185',field_op_3: '',field_val_3: accountManager,
      field_id_4: 'field_39',field_op_4: '',field_val_4: projectManager,
      field_id_5: 'field_169',field_op_5: '',field_val_5: site,
      field_id_6: 'field_40',field_op_6: '',field_val_6: type,
      field_id_7: 'field_178',field_op_7: 'is not',field_val_7: 'cancelled ',
      field_id_8: 'field_41',field_op_8: 'is after',field_val_8: dateStart,
      field_id_9: 'field_43',field_op_9: '',field_val_9: dateEnd,
      field_id_10: 'field_771',field_op_10: '',field_val_10: '', // Use 'field_771_raw' for sum aggregation
    },
     function(type, response, xhrResponse) {
      console.log('TriggerPipe response:', response); // Log the raw response data

      var parsedData = parsePipeData(response);
      console.log('Parsed data:', parsedData); // Log the parsed data

      var filteredData = filterData(parsedData, searchQuery);
      console.log('Filtered data:', filteredData); // Log the filtered data

      var updatedColumnDefs = updateColumnDefs(columnDefs, filteredData);
      console.log('Updated column definitions:', updatedColumnDefs); // Log the updated column definitions

      gridOptions.api.setColumnDefs(updatedColumnDefs);
      gridOptions.api.setRowData(filteredData);
    }
  );
}
// Function to parse the pipe data into a usable format
function parsePipeData(response) {
  return response.items.map(function(item) {
    var result = {};
    Object.keys(columnConfig).forEach(function(headerName) {
      var field = columnConfig[headerName].field;
      if (field === 'field_169_val') {
        if (Array.isArray(item[field])) {
          result[field] = item[field][0].val;
        } else {
          result[field] = item[field];
        }
      } else {
        result[field] = item[field];
      }
    });
    return result;
  });
}
// Function to filter the data based on the search query
function filterData(data, searchQuery) {
  return data.filter(function filterItem(item) {
    for (var key in searchQuery) {
      if (searchQuery.hasOwnProperty(key) && item.hasOwnProperty(key)) {
        if (key === 'field_41') {
          var fieldValue = new Date(new Date(item[key]).setUTCHours(0, 0, 0, 0));
  var queryValue = searchQuery[key];

          if (queryValue['$gte'] && fieldValue < new Date(queryValue['$gte'])) {
            return false;
          }
          if (queryValue['$lte'] && fieldValue > new Date(queryValue['$lte'])) {
            return false;
          }
        } else {
          var fieldValue = item[key];
          var queryValue = searchQuery[key];
          if (typeof queryValue === 'string' && typeof fieldValue === 'string') {
            if (!fieldValue.toLowerCase().includes(queryValue.toLowerCase())) {
              return false;
            }
          } else if (typeof queryValue === 'number' && fieldValue !== queryValue) {
            return false;
          }
        }
      }
    }
    return true;
  });
}

// Function to update column definitions based on the filtered data
function updateColumnDefs(columnDefs, filteredData) {
  return columnDefs.map(function(colDef) {
    var definition = Object.assign({}, colDef);
    if (filteredData.length > 0 && filteredData[0].hasOwnProperty(colDef.field)) {
      definition.hide = false;
    } else {
      definition.hide = true;
    }
    return definition;
  });
}

// Function to check if at least one input field is filled
function checkInputs(inputs) {
  var hasInput = inputs.some(function(input) {
    return input.value.trim() !== '';
  });
  if (!hasInput) {
    alert('Please fill in at least one field before searching.');
    return false;
  }
  return true;
}

Converting string to number not working in Javascript

I’m confused.

$("#total-kwh-cost").text() contains the text $920. It has been previously calculated and formatted using toLocaleString() as USD currency and stored in a div with an id of #total-kwh-cost.

I retrieve the text from the div using:

var tkwhCostp = $("#total-kwh-cost").text().replace(/,/g,''); // returns $920 as text

Then I check it to make sure it’s been a number

console.log("tkwhCostp text is: "+tkwhCostp);       // return NaN
console.log("tkwhCostp isNAN? "+isNaN(tkwhCostp));  // returns true
tkwhCostp = parseFloat(tkwhCostp);                  // Run it through parseFloat
console.log("tkwhCostp text is: "+tkwhCostp);       // returns NaN  
console.log("tkwhCostp isNAN? "+isNaN(tkwhCostp));  // returns true

I tried parseInt() and Number() and get the same results. This has to be local to my code.

It also appears to only affect variables that I converted using toLocaleString().

I’m at a loss as to how to convert it back to a number so I can add to the number 920.

Copying files within Electron application results in ‘no such file or directory’ error. How to fix?

I am trying to copy a file to a folder in my Electron application but I keep getting a no such directory/file error.

I am new to this, so I could be missing something completely obvious. I keep getting this error,

`Failed to copy the file: [Error: ENOENT: no such file or directory, copyfile       'C:UsersAJSWIDownloadsunnamed.png' -> 'C:UsersAJSWIDesktopCollege    NotesCollegeNotesClassesF2324Mathunnamed.png'] {

errno: -4058,
code: ‘ENOENT’,
syscall: ‘copyfile’,
path: ‘C:UsersAJSWIDownloadsunnamed.png’,
dest: ‘C:UsersAJSWIDesktopCollege NotesCollegeNotesClassesF2324Mathunnamed.png’
}`

I have double checked everything that I could think of, the path exists, I removed the name at the end of the destination, and I even asked ChatGPT which went nowhere.
here is the function I use to check and copy the file.

  • btw the console.log passed check appears in the console –

`fs.access(noteFile, fs.constants.F_OK, (err) => {
if (err) {
console.error(‘Source file does not exist:’, err);
return;
}
console.log(“Passed Check – “, noteFile);

fs.copyFile(noteFile, destination, (err) => {
if (err) {
console.error(‘Failed to copy the file:’, err);
return; }
console.log(‘File copied to:’, destination);
});

});`

how to add user in react js?

hello guys am working on project and i have made component addusers i try this on postman with api it works perfectly. but when i implement in code its giving error (Failed to add user: SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON)

import React, { useState } from "react";

const AddUser = ({ setTokenValue }) => {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (event) => {
    event.preventDefault();
    setIsSubmitting(true);

    try {
      const response = await fetch("https://api.store.ellcart.com/users", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer <eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwaS5zdG9yZS5lbGxjYXJ0LmNvbS91c2Vycy9sb2dpbiIsImlhdCI6MTY4NTYzNDY1MCwibmJmIjoxNjg1NjM0NjUwLCJqdGkiOiJBZ2doWFpiT1VxeGF4QTBvIiwic3ViIjoiMjA0IiwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.28tizEstlORenFGcDin-3RSFgtHzJpnoA2UYI7A2sJ0>`,
        },
        body: JSON.stringify({
          name: name,
          email: email,
          phone: phone,
          password: password,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to add user");
      }

      const data = await response.json();

      if (data && data.authorisation && data.authorisation.access_token) {
        const token = data.authorisation.access_token;
        setTokenValue(token);
        setName("");
        setEmail("");
        setPhone("");
        setPassword("");
        setErrorMessage("");
      }
    } catch (error) {

      setErrorMessage(error.message);
      console.error("Failed to add user:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {errorMessage && <p>{errorMessage}</p>}
      <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </label>
      <label>
        Email:
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      <label>
        Phone:
        <input type="phone" value={phone} onChange={(e) => setPhone(e.target.value)} />
      </label>
      <label>
        Password:
        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      </label>
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? "Submitting..." : "Add User"}
      </button>
    </form>
  );
};

export default AddUser;

i request please help me to get my fact clear.

MongoDB: I’m using find() to get a specific value but instead getting multiple results

Working on a Facebook clone and I’m setting up uploading a profile picture. I have a User schema with a profilePicture object. The user visits the page, uploads a picture and that image URL gets added to their profilePicture value.

User schema

const userSchema = new mongoose.Schema({
  username: String,
  profilePicture: String,
});

Here’s an example of what a User looks like in the DB.

_id: 642716b83w306234dx8d6cab
username: "Dagger"
profilePicture: "publicimagesuploadsa7c770ff72d830a4fb0c8f6963ab9aa8"

And here is the GET request for my profilePicture. What I’m doing is using User.find() to find the profilePicture

router.get("/:user/profile-picture", (req, res) => {
  User.find({}, "profilePicture").exec(function (err, profilePicture) {
    if (err) {
      return next(err);
    }
    res.render("picture", { user, id, picture, profilePicture });
  });
});

but when I add the img code to the ejs page nothing shows up.

<div class="avatar">
  <img src="<%= profilePicture %>.jpg" alt="logo" />
</div>

When I inspect the element I notice the value of <%= profilePicture %> is a list of every User in my database. How can I narrow it down so I only get the value set to "publicimagesuploadsa7c770ff72d830a4fb0c8f6963ab9aa8"?

Mongoose retrieve all documents that are not referenced in the same collection’s array field

I have the below Post schema. The post schema contains an array field that may contain other posts as replies. What I would like to do is retrieve all documents which are not referenced in any post’s replies field. Basically get all posts that are not replies of an original post.

const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        validate: [mongoose.Types.ObjectId.isValid, 'Creator ID is invalid']
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        validate: [mongoose.Types.ObjectId.isValid, 'Owner ID is invalid']
    },
    content: {
        type: String,
        required: 'Content is required'
    },
    likes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Like',
            validate: [mongoose.Types.ObjectId.isValid, 'Like ID is invalid']
        }
    ],
    replies: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post'
        }
    ]
}, {
    autoCreate: true,
    timestamps: true
});

const Post = mongoose.model('Post', schema);

module.exports = Post;

I have tried using $lookup with $match & $nin but I cannot make it work properly. Any help would be greatly appreciated.