Going through the react-router tutorial and rather than using default or null values when loading an empty object, it kicks up an error

I’ve been going through react-router’s tutorial, and I’ve been following it to the letter as far as I’m aware. I’m having some issues with the url params in loaders segment.

The static contact code looks like this

export default function Contact() {
  const contact = {
    first: "Your",
    last: "Name",
    avatar: "https://placekitten.com/g/200/200",
    twitter: "your_handle",
    notes: "Some notes",
    favorite: true,
  }

And when it loads, it looks like this. That works just fine, however, the tutorial then tells me to change that code so that I use data that’s loaded in instead. The code now looks like this

import { Form, useLoaderData } from "react-router-dom";
import {getContact} from "../contacts"

export async function loader({ params }){
  const contact = await getContact(params.contactid);
  return {contact}
}

export default function Contact() {
  const {contact} = useLoaderData();

According to the tutorial, it should just load in an empty contact that looks like this but instead, every time I try to open one of the new contacts, it kicks up an error saying

React Router caught the following error during render TypeError: contact is null

The actual line of code this error points to is in the return segment of the contact component, which looks like this

return (
    <div id="contact">
      <div>
        <img
          key={contact.avatar}
          src={contact.avatar || null}
        />
      </div>

      <div>
        <h1>
          {contact.first || contact.last ? (
            <>
              {contact.first} {contact.last}
            </>
          ) : (
            <i>No Name</i>
          )}{" "}
          <Favorite contact={contact} />
        </h1>

        {contact.twitter && (
          <p>
            <a
              target="_blank"
              href={`https://twitter.com/${contact.twitter}`}
            >
              {contact.twitter}
            </a>
          </p>
        )}

        {contact.notes && <p>{contact.notes}</p>}

        <div>
          <Form action="edit">
            <button type="submit">Edit</button>
          </Form>
          <Form
            method="post"
            action="destroy"
            onSubmit={(event) => {
              if (
                !confirm(
                  "Please confirm you want to delete this record."
                )
              ) {
                event.preventDefault();
              }
            }}
          >
            <button type="submit">Delete</button>
          </Form>
        </div>
      </div>
    </div>
  );
}

Pretty much anywhere contacts is called gets an error. So, anyone have any idea what I’m doing wrong here? To my knowledge, I’ve been following their guide to the letter and it seems like it should be able to handle contacts not having any data, but it’s not.

When I do innerHTML it does not log when I submit. Why?

I am trying to make a design idea kind of like a AI site where you can talk to a script. This is a simple form which is supposed to output a certain sentence based on the option chosen, but when I press submit, no output is provided. I tried using ID and Class, and that didn’t work. Code is below:

function Use() {
        var option = document.getElementsByClassName("LANG").value;
        if (option === "HTML") {
        document.getElementsByClassName("usable").innerHTML = "The standard web markup language."
        }else if(option === "CSS") {
        document.getElementsByClassName("usable").innerHTML = "The standard web stylesheet language."
        }else{
        document.getElementsByClassName("usable").innerHTML = "The standard web scripting language."
        }
    }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="docs.js"></script>
<title>Browser</title>
</head>
<body>
<form action="docs.html" onsubmit="return Use()">
<label><input class="LANG" type="radio" value="HTML">HTML</label>
<label><input class="LANG" type="radio" value="CSS">CSS</label>
<label><input class="LANG" type="radio" value="JS">JS</label>
<button>Submit</button>
<p class="usable"></p>
</form>
</body>
</html>

React MUI Dropdown menu in side persistent Drawer not showing item list

I integrated a React MUI dropdown select menu in a persistent Side Drawer, but I encountered an issue where I couldn’t see the menu list when attempting to select an option while the Drawer was open. However, when I closed the Drawer, the menu list appeared behind it.

Here is the sandbox link

Steps to reproduce

  1. Click the menu button
  2. Try to open the dropdown menu inside the drawer
  3. Close the drawer

How can I simplify my jQuery code to avoid repeating instructions?

Novice trying to simplify my jQuery, to avoid repetition

I am a novice with Javascript and jQuery, but have written some code to display a tooltip on a form depending on the answer selected to a dropdown. Right now I am repeating the steps twice:

  1. Once to check the dropdown on page load, in case it has reloaded due to a submission error – in this case, if an answer has been selected to that question, it will persist, and I need the tooltip to remain.

  2. Once to check whenever the dropdown value changes.

The value of the dropdown is a number, so I’ve used that in the div classes to show the appropriate div. This is the code which is working fine:

$(document).ready(function(){
    var service = "";
    var otherservice = "";

    // Check for select value on page load, in case it has refreshed due to a form error

    service = '.v' + $('select#989022_58716pi_989022_58716 option:selected').val();
    otherservice = '#form-tooltips div:not('+service+')';
    $('#form-tooltips div'+service).show();
    $(otherservice).hide();

    // Check again for select value, every time that selection changes

    $('select#989022_58716pi_989022_58716').on('change', function(){
        service = '.v' + $('select#989022_58716pi_989022_58716 option:selected').val();
        otherservice = '#form-tooltips div:not('+service+')';
        $('#form-tooltips div'+service).show();
        $(otherservice).hide();
    });
});

//The tooltips for display

$("<div id='form-tooltips'><div class='v1381962'>Tooltip 1</div><div class='v1381965'>Tooltip 2</div></div>").insertAfter(".add-tooltip-after");

What I would like to do is create a function – checkTooltip – so that I do not have to repeat those tooltip instructions the second time. I have tried the following:

$(document).ready(function(){
    var service = '';
    var otherservice = '';
    function checkTooltip({
        service = '.v' + $('select#989022_58716pi_989022_58716 option:selected').val();
        otherservice = '#form-tooltips div:not("+service+")';
        $('#form-tooltips div'+service).show();
        $(otherservice).hide();
    });
    checkTooltip();
    $('select#989022_58716pi_989022_58716').on('change', checkTooltip());
});
$("<div id='form-tooltips'><div class='v1381962'>Tooltip 1</div><div class='v1381965'>Tooltip 2</div></div>").insertAfter(".add-tooltip-after");

However this is not working. In the Chrome console, it says Uncaught SyntaxError: Unexpected token ‘;’ on the 5th line. I have tried removing that semicolon but then it gives me Unexpected identifier ‘otherservice’ instead.

Am I completely misunderstanding how this works or making some kind of syntax error? Many thanks in advance to anyone who can help!

SyntaxError: Unexpected token ‘*’ error when i try to load my javascript

i am getting this error SyntaxError: Unexpected token ‘*’. import call expects exactly one argument. when i load my javascript file in my django project.

this is my code btw

import * as THREE from 'three';

 const scene = new THREE.Scene();
 const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000);
 const renderer = new THREE.WebGLRenderer({
    canvas: document.querySelector("#bg"),

 });
 renderer.setPixelRatio(window.devicePixelRatio);
 renderer.setSize(window.innerWidth,window.innerHeight);
 camera.position.setZ(30);
 renderer.render(scene,camera);

 const geometry = new THREE.OctahedronGeometry(1,0);
 const color = new THREE.Color(134, 0, 255);
 const mat = new THREE.MeshBasicMaterial({color: color,wireframe: true});
 const torus = new THREE.Mesh(geometry,mat);

 scene.add(torus);
 function animate(){
    requestAnimationFrame(animate);
    renderer.render(scene,camera);
 }
 animate()

i have already tried: looking if i have the correct javascript version that supports import i have and looking if i load the file correctly and triple checking if i have installed three correctly aswell. but for some reason it just does not work.

Is there an efficient way to translate input text into English using an API or JavaScript method?

Is there an API that translates input texts into English? This are my first projects with API’s.
I have built a project with an API. The user should enter the country in the input. Since the API only has all country names in English, I left it so that the country should always be entered in English.

Is there an API that translates the input or maybe a method in Javascript that translates the strings into another language?

Here is my Project.

https://emxrxan.github.io/Land/

Django – INTEGRITY ERROR on column that no longer exists

I am getting this error:

IntegrityError at /register/
null value in column "total_daily_mission_progress" violates not-null constraint
DETAIL:  Failing row contains (363, 0, 374, free, 0, null, unranked, 0, , [email protected], 0, f, [], 0, {}, {}, t, null, null, null, null, null, {}, null, null, No phone number set, This user has not set a description yet., /static/images/profilepictures/defaultavatar.png, {}, {}, {}, {}, {}, 0).

However, the column total_daily_mission_progress no longer exists in my UserDetail model. I deleted it a while ago and migrated. However, this issue comes up every time I try to create a new UserDetail model.

Why is this occuring? I don’t have the total_daily_mission_progress anywhere in my code. And how can I fix it?

Typescript – How to import and use RequestInit type from fetch?

I want to create a custom fetchServer method in which I can manipulate the different parameters (such as the URL, headers, and so on) in my React application before performing the actual fetch.

This method, at the end, uses the common fetch from Javascript, which has the following signature:

function fetch(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>

So, I’ve written my fetchServer this way:

export const fetchServer = async <T>(
  url: string,
  options: any = {},
): Promise<T> => {
  ...
  const alteredOptions = { ...options, /* my custom code */ };
  const rawResponse = await fetch(url, { ...alteredOptions});
  ...
};

However, as you can see, I’m using any for options, because I’m unable to import successfully the RequestInit type from anywhere.

I’ve read this issue, but it’s from apollo package (which I’m not using) and it’s not solved.

I can try to declare it myself, but then the same happens with body and headers properties (which have BodyInit and HeadersInit types).

I’ve also tried to reference it directly, but ESlint throws an error because it’s undefined and VSCode seems unable to import it correctly (although it autocompletes it).

interface RequestInit
'RequestInit' is not defined : eslint(no-undef)

How should I type my options parameter so that it extends the RequestInit type parameter of fetch method, and I’m able to extend it with my own properties?

Handling form data and adding it to agGrid

I have a page that contains a modal with a form. One of the elements on the form is an ag-grid where it saves each row as an array of objects and then passes that back to another grid on the original page. When sending the data back it continues to not display the array of objects correctly in the original page grid. I’m receiving a [Object object] is not valid JSON.

This is how the data is being put together for passing back to the original grid.

newParameters = [];

$dashboardParametersGrid.api.forEachNode((rowNode, index) => {

    if (rowNode.data.table && rowNode.data.column && rowNode.data.columnValue) {

        var parameter = {table: rowNode.data.table, column: rowNode.data.column, columnValue: rowNode.data.columnValue};

        JSON.stringify(parameter);

        newParameters.push(parameter);

    }

});

let client = {};
console.log(newParameters);
client['parameters'] = newParameters;

I’m tried client['parameters'] = JSON.parse(newParameters) and client['parameters'] = JSON.stringify(newParameters).

How to render a partial html response

I am calling an endpoint as follows in my React project via fetch.

curl –location ‘https://example.com/some/v1’
–header ‘Content-Type: text/html’

This give me a response like: (It is over 5000 lines, just showing part of it).

<style class="ssr-css">
    .some_class {
        margin: 0 auto
    }

    html,
    body {
        overflow-x: hidden;
        width: 100%;
        height: 100%
    }
    /* 100+ more styles */
</style>
<style class="ssr-css">
    .some_class_1 {
        margin: 0 auto
    }
    /* 600+ more styles */
</style>
<div class="some_class">
    <div style="color: red" class="some_class_1">
        some text
    </div>
    <!-- 1000's more lines -->
</div>

How can I convert this to be a component and render it?

I can’t just use dangerouslySetInnerHTML. It will handle the html fine but not the styles.

I could consider something like the following to extract the styles and directly inject to document.

Feels bit hacky and worry this will have side effects on other stylings on my page.

Anyway I could do this using React, without having to directly inject styles to document. A cleaner approach.

Please advice, thanks.

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

const MyComponent = () => {
  const [htmlResponse, setHtmlResponse] = useState('');

  useEffect(() => {
    fetch('https://example.com/some/v1', {
      headers: {
        'Content-Type': 'text/html',
      },
    })
      .then((response) => response.text())
      .then((data) => setHtmlResponse(data))
      .catch((error) => console.error(error));
  }, []);

  useEffect(() => {
    const styleRegex = /<styleb[^>]*>([sS]*?)</style>/gm;
    const matches = [...htmlResponse.matchAll(styleRegex)];
    const styles = matches.map((match) => match[1]).join('');

    const styleElement = document.createElement('style');
    styleElement.innerHTML = styles;
    document.head.appendChild(styleElement);
  }, [htmlResponse]);

  return (
    <div dangerouslySetInnerHTML={{ __html: htmlResponse }} />
  );
};

export default MyComponent;

Typescript – assigning array containing object reference

I’m trying to assign an array to an object that contains an object which is not yet defined, and I don’t really understand why it doesn’t work. I thought objects in Javascript are passed by reference, but it stays undefined in this case.
I’m calling a method like this:

this.myField = new InputField(...)
.withRevalidateOtherFields([this.otherField]);

this.otherField = new InputField(...);
console.log(this.myField.otherFieldsForRevalidation); // <-- [undefined]

The console output shows that the assigned field is still undefined, although it should have been passed by reference and the reference contains a valid object at that point.

The method assigns the parameter to private field:

  public withRevalidateOtherFields(fields: InputField[]): this {
    this.otherFieldsForRevalidation = fields;
    return this;
}

Of course I could call the method only after all fields point to a valid object, but this would make the code more complicated.
Any ideas why it doesn’t work like that?

Javascript remove properties and nested properties from an object

let object = {
   "a": {id: 1},
   "b": {age: "21"},
   "c": {score: 3, length: "Three", name: "One"},
   "d": {birthday:"03/01"}
}

what I want to return is:

object = {
   "b": {age: "21"},
   "c": {length: "Three"}
}

Here is my current code:

const removeProps = (obj: Object): Object => {
        const copy = { ...obj}
        const removedProps: Set<string> = new Set(['a', 'd']);
        const removedNestingProps: Set<string> = new Set(['name', 'score']);
        for (const key of Object.keys(copy)) {
            if (removedProps.has(key)) {
                delete copy[key];
            } else {
                if (key === 'c'){
                    for (const nestedKey of Object.keys(copy[key])){
                        if (removedNestingProps.has(nestedKey)){
                            delete copy[key][nestedKey];
                        }
                    }
                }
            }
        }
        return copy;
    }

Is there a better way to achieve this? I have a lot of properties in the object for my project and just gave an easy object as an example here. Thanks for the help!!

How can I send data from view to controller in ASP.NET MVC?

This is my cshtml code. This code prints selected data from select list into textbox.

                        <tr>
                            <td><label>CC</label></td>
                            <td><input class="form-control input-sm" type="text" name="name" id="[email protected]" value="" @(item.SelectedSpecs.Count > 0 ? "disabled" : "") /></td>
                        </tr>
                        @{
                            int selectid = item.id;
                        }
                        <tr>
                            <td><label></label></td>
                            <td>
                                <select id="mySelect_@selectid" onchange="selectToInput(this)">
                                    <option value="">Kişi Seçiniz...</option>
                                    @foreach (var x in item.kullaniciIsimleri)
                                    {
                                        string value1 = x;
                                        <option value="@value1">@x</option>
                                    }
                                    <option value="TECTURA">TECTURA</option>
                                </select>
                            </td>
                        </tr>

This is my javascript code that allows me to do this.

        <script>
            function selectToInput(elem) {
                var selectValue = elem.value;
                var inputId = elem.id.replace("mySelect", "myInput");
                document.getElementById(inputId).value = selectValue;
        </script>

Here, on the same html page, I send some values ​​to the post method in my controller by pressing the “ask a question” button.

                    <div class="cord-footer">
                        <hr />
                        <form id="@item.id+formdata" action="@Url.Action("Ask_Question", "Question")" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <input type="hidden" name="ItemId" value="@item.id" />
                                <input type="hidden" name="pid" value="@Model.ProjectId" />
                                <input type="hidden" name="itemspecs" value="" />
                                <input type="hidden" name="isinit" value="@item.SelectedSpecs.Count" />
                                <input type="hidden" name="questiontype" value="0" />
                                <input type="hidden" name="sendertype" value="0" />

                                <label>Ask Question</label>
                                <textarea name="Message" class="form-control" required></textarea>
                            </div>
                            <input type="file" name="FileContent" class="form-control" />
                            <br />
                            <div class="text-right">
                                <input type="submit" data-type="askquestion" class="btn btn-kreon" value="Ask Question" />
                                <label class="pull-left" data-type="collapseQuestions">Conversation <span class="glyphicon glyphicon-chevron-up"></span></label>
                            </div>
                        </form>
                    </div>

And this is my controller method.

        [HttpPost]
        public ActionResult Ask_Question(Zenon_data_PeraPortalPeraItemProItemQues question, HttpPostedFileBase FileContent, int pid, string itemspecs, int isinit, int questiontype, string CC,int sendertype, string formElement)
        {
            if (String.IsNullOrEmpty(question.Message))
                return RedirectToAction("ListQuestionList", "Question", new { pid = pid });

           
            var project = _db.Zenon_data_PeraPortalPeraItemProject.FirstOrDefault(s => s.id == pid);
            var item = _db.Zenon_data_PeraPortalPeraItemProjectItem.FirstOrDefault(s => s.ID == question.ItemId);

            if (isinit == 0)
            {
                var sales = questiontype % 2 == 0;
                var tech = questiontype % 2 == 1;
                Init_QuestionItem(question.ItemId, itemspecs);
                item.is_Sales = Convert.ToByte(sales);
                item.is_Tech = Convert.ToByte(tech);
                
            }
            question.Date = DateTime.Now;
            question.Sender = User.User_ID;
            question.File = SaveFile(FileContent, pid, project.Name);
           
            question.Type = "";
           
            _db.Zenon_data_PeraPortalPeraItemProItemQues.Add(question);

            _db.SaveChanges();
            if(sendertype==0)
            return RedirectToAction("ListQuestionList", "Question", new { pid = pid });
            else if (sendertype == 1 && item.is_Tech == 1)
                return RedirectToAction("TechQuestionList", "Question", new { pid = pid });
            else if (sendertype == 1 && item.is_Sales == 1)
                return RedirectToAction("SaleQuestionList", "Question", new { pid = pid });
            else
            return RedirectToAction("ListQuestionList", "Question", new { pid = pid });
        }

My problem is that; I can’t send the data I get from the selectlist to the controller. While doing this, I don’t want to completely enclose the block I want to submit in the form tag. Can I just take the value of the element I want to send and keep it in the form tag?

I wrote a lot of javascript code to keep the value of the element I want to send and assign it to a variable, but I couldn’t get any results.