Why am I getting a Typescript type error for a Date field?

I have the following Typescript function:

  isAttendanceDuplicate(date: Date, attendances: Attendance[]): boolean {
    const dateValues = new Array<number>();
    attendances.filter(as => as.isHidden === false).forEach(a => {
      const attendanceDate = new Date(a.date.getFullYear(), a.date.getMonth(), a.date.getDate());
      dateValues.push(attendanceDate.valueOf())
    });
    const matchingDateVales = dateValues.filter(d => d === date.valueOf());

    return matchingDateVales.length > 0;
  }

And this is the definition for an attendance:

export class Attendance {
  calendarItemId: string;
  calendarItemTypeId: number;
  hasNoDueEvent: boolean;
  clientId: string;
  dueEventId: string;
  resultEventId: string;
  calendarItemName: string;
  type: number;
  status: number;
  date: Date;
  isHidden: boolean;
  statusName: string;
  hasOpenAlert: boolean;
}

As you can see in that class date is a Date.

When attempting to create a new Date (attendanceDate) I get the following error:

“TypeError: a.date.getFullYear is not a function.” Why?

React onClick attribute not triggering when using react-scripts, but working fine when running with Webpack

I have a simple react app that updates some state upon a button press. Something like this:

export default function App() {
  const [thing, setThing] = useState(0)

  function updateState() {
    setThing(1);
    console.log(thing);
  }


  function renderButtons() {
    return (
      <div class="btnDiv">
          <div>
          <Button onClick={() => updateState()}>Yes</Button>
          </div>
          <div>
          <Button theme="pink" onClick={() => updateState()}>
            No
          </Button>
        </div>
        </div>
    )
  }

  return (
  <>
    
    <p>
    Press a button
    </p>
    
    {renderButtons()}
  </>
  );
}

Basically, when one of the buttons defined in renderButtons() is pressed, the thing variable should be updated and logged to the console. When I run this using webpack-dev-server . the project works as expected and the console logs appear as they should. However, when I run this same program with react-scripts start, the logs don’t appear at all. It is almost as if the onClick attribute assigned to the buttons is not triggered when the buttons are pressed. I have no clue why the program would work with one set of run scripts and not another. Any help would be appreciated.

Is this the wrong way of handling array of objects from api call?

I am trying to store a array of names from a json response containing an array of objects.

For some reason the printing array will have nothing inside.Is this the correct way of doing it.
Its not working for some reason otherwise no errors.

also the forEach is loop not even running once i tested it.


useEffect(() => {
  
    instance.get('/')
    .then(function (response) {
      // handle success
      //console.log(response);
      console.log(response.data);
      (response.data).forEach(newValue=>
        {
          setArray(oldArray => [...oldArray,newValue.name])
        }
      )
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      console.log("printing array 1",Array);
      // always executed
    });
    
    if(Array)
    console.log("printing array 2",Array);
    
  },[]);

Call Javascript functions from variable string name

I am looking for the best method of calling functions with variable names that all follow a specific rule. I am trying to avoid using eval() since there are so many problems about it online.

I have a system setup where different groups have a function that can be called based on their name EG Test group would have a function imported in called getValue_Test(params) and this function can be called for any group name EG getValue_Test2(params) would work if the group name was test2.

I have these functions being imported into the react component and just want to know the best way to call them without making giant switch statement since there will be hundreds of these functions.

Any help would be appreciated 🙂 Thanks

Why cant have a variable string inside my regex? [duplicate]

Hi,

I have this code:

var regcat = /b(aa1)[a-z]d+[.][g][i][f]b/;
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

it produces TRUE which is fine. However what I really need is to replace the “a1” in the regex with a variable, like this:

var catvar = "a1";
var regcat = "/b(a"+catvar+")[a-z]d+[.][g][i][f]b/";
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

but I cant make it work so I tried this also:

var catvar = "a1";
var regcat = RegExp("/b(a"+catvar+")[a-z]d+[.][g][i][f]b/","g");
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

but nothing works. What am I doing wrong?

Thank you.

Call function inside module on javascript?

I’m starting a project that uses three.js library, and I will use also a parallax library. The 3D effects will be only decorative, but parallax will trigger it.

I modified this example and works fine for me:
demo: https://threejs.org/examples/#webgl_geometry_text_shapes
code: https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_text_shapes.html

…but I need to send the title of every section (when the user enter on it by scrolling down) to the 3D script code, and it is closed inside a module.

…How to to it? I’m newbie into three.js and modules, and want to keep the parallax as is (outside module, because it’s a well-known library and part of developed yet project)

Maybe the right way is transform the sample code, without modules… but I’m lost with it… for example, the starting part of JS in module, are:

import * as THREE from 'three';

import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { SVGLoader } from './jsm/loaders/SVGLoader.js';
import { FontLoader } from './jsm/loaders/FontLoader.js';

…how to do it without modules / import?

Thanks in advance

ToDo app – how to link the members list to the tasks list

I am trying to select the member’s name and link it to the task list so that the user wont be able to write a task unless they select a name.
also, i want to save the members’names and tasks in an array and be able to remove names and tasks from the localStorage and the array.

here is the html:

<div class="mainText">
    <h1>Family todo list</h1>
</div>

<div class="mainAppElements">
    <!--NAME ELEMENTS--> 
    <div class="family_members">
        <h4>Add family members</h4>
        <input class="family_member_name" id="family_member_name" />
        <button class="addMemberButton buttonStyle" id="addMemberButton">Add member</button>
        <div class="familyMembersList elementsContainer">
            <ul id="familyMembersList">
                <div>All Members</div>
            </ul>
            
        </div>
    </div>
    
    <!--TASK ELEMENTS-->
    <div class="Member_task">
        <h4>Add Tasks</h4>
        <input class="task_name" id="task_name" />
        <button class="addtaskButton buttonStyle" id="addtaskButton">Add task</button>
        <div class="allTasksList elementsContainer">
            <ul id="allTasksList">
                <div>All Tasks</div>
            </ul>
        </div>
    </div>
</div>

here is the javaScript:

let memberNameArray = [];
let nameValues;

function addMembersClickHandler() {
const addMembersInputElement = document.getElementById("family_member_name");
const memberNameValue = addMembersInputElement.value;


const membersList = document.getElementById("familyMembersList");
if (memberNameValue !== "") {
    //user name
    const memberName = document.createElement("p");
    memberName.innerText = memberNameValue;
    //select user button
    const selectButton = document.createElement("button");
    selectButton.classList.add("unselectButton");
    selectButton.innerText = "Select";
    selectButton.addEventListener("click", function () {
        // toggel the color
        // The following 7 lines of code was adapted from https://stackoverflow.com/questions/47633130/javascript-replace-classlist-that-is-into-a-conditional Accessed: 2022-04-30
        if (selectButton.classList.contains("unselectButton")) {
            const onSelect = selectButton.classList.replace("unselectButton", "selectButton");
            return onSelect;
        } else if (selectButton.classList.contains("selectButton")) {
            const unSelect = selectButton.classList.replace("selectButton", "unselectButton");
            return unSelect;
        }
    })
    //remove user button
    const removeUserButton = document.createElement("button");
    removeUserButton.innerText = "Remove";
    removeUserButton.classList.add("removeButton");
    removeUserButton.addEventListener("click", function() { 
        let result = membersList.removeChild(userInfoElement);
        

        for (let memberNameIndex in memberNameArray) {                
            console.log(memberNameIndex);

            nameValues = document.getElementsByTagName("p");
            nameValues = memberNameArray[memberNameIndex];
            memberNameArray.splice(memberNameIndex, 1);
        }
        
        return result;
    })
    
    //display things
    const userInfoElement = document.createElement("div");
    membersList.appendChild(userInfoElement);
    userInfoElement.appendChild(memberName);
    userInfoElement.appendChild(selectButton);
    userInfoElement.appendChild(removeUserButton);
    //style things
    userInfoElement.style = "display: flex; flex-direction: row; justify-content: left;";
    //store things (ask in lab)
    memberNameArray.push(memberNameValue);
    let arrayElements = JSON.stringify(memberNameArray);
    localStorage.mm = arrayElements;
    addMembersInputElement.value = "";
} else {
    alert("Pleas Enter a Name")
}
}

function addTasksClickHandler() {
const addTasksInputElement = document.getElementById("task_name");
const taskNameValue = addTasksInputElement.value;

const tasksList = document.getElementById("allTasksList");

if (taskNameValue !== "") {
    //user name
    const taskName = document.createElement("p");
    taskName.innerText = taskNameValue;
    taskName.classList.add("p");
    //done button
    const doneButton = document.createElement("button");
    doneButton.classList.add("doneButton");
    doneButton.innerText = "Done";
    doneButton.addEventListener("click", function () {
        if (taskName.classList.contains("p")) {
            const drawLineOnTask = taskName.classList.replace("p", "doneTasks");
            return drawLineOnTask;
        } else if (taskName.classList.contains("doneTasks")) {
            const normalTaskNameStyle = taskName.classList.replace("doneTasks", "p");
            return normalTaskNameStyle;
        }
    })
    //remove button
    const removeTaskButton = document.createElement("button");
    removeTaskButton.innerText = "Remove";
    removeTaskButton.classList.add("removeButton");
    removeTaskButton.addEventListener("click", function() { 
        let result = tasksList.removeChild(taskInfoElement);
        return result;
    })
    //display things
    const taskInfoElement = document.createElement("div");
    tasksList.appendChild(taskInfoElement);
    taskInfoElement.appendChild(taskName);
    taskInfoElement.appendChild(doneButton);
    taskInfoElement.appendChild(removeTaskButton);
    //style things
    taskInfoElement.style = "display: flex; flex-direction: row; justify-content: left;";

    addTasksInputElement.value = "";
} else if (taskNameValue === "") {
    alert("Please Enter a task");
}
}


function loadHandler() {
const addMemberButton = document.getElementById("addMemberButton");
addMemberButton.addEventListener("click", addMembersClickHandler);

const addTaskButton = document.getElementById("addtaskButton");
addTaskButton.addEventListener("click", addTasksClickHandler);
}

window.addEventListener("load", loadHandler);

how to increase the number of rows

what do i do so that the number in front of the row created changes(increases) as more rows are added

 <table id="sampleTable" border="1">
      <tr>
        <td>Row1 cell1</td>
        <td>Row1 cell2</td>
      </tr>
      <tr>
        <td>Row2 cell1</td>
        <td>Row2 cell2</td>
      </tr>
    </table>
    <br />
    <input type="button" onclick="insert_Row()" value="Insert row" />

const insert_Row=()=>{
    const table= document.querySelector('#sampleTable');
   const row=table.insertRow();
   const cell1=row.insertCell().textContent='Row2 cell1'
   const cell2=row.insertCell().textContent='Row2 cell2'
 return cell1&&cell2
}

Material ui Dialog onClick deletes only last index

So I’ve created a get request, which shows all the exercises and the options to edit (which will redirect to another url) and delete. I wanted to use material ui’s Dialog, so there will be a confirmation before deleting. The problem is that, say I have 3 exercises and want to delete exercise with index 1, when click the on delete button it appears the last index in the element i.e the last exercise, although I want to delete the second. How can I fix that?
And also can I move Dialog in another file for more clear coding?

Exercises.js

const Exercises = () => {
const { categories, deletedCategories, error, isLoading, exercises, open, handleClickOpen, handleClose, deleteExercise } = useFormExercises();
const [showCategories, setShowCategories] = useState(false);

if (isLoading) {
    return <div>Loading...</div>
}
if (error) {
    return <div>There was an error: {error}</div>
}

return (
    <Grid container  className='content' >
        <Card className='exerciseCard'>
            <h1>Exercises</h1>
                <FormControlLabel sx={{ width:'500px'}}
                    label="Show Categories"
                    control={
                        <Checkbox
                            sx={{ml:2}}
                            checked={showCategories}
                            onChange={(event) => setShowCategories(event.target.checked)}
                        />
                    }
                />
                <Button sx={{pr:6}}  variant='fab' href={('/exercises/add')}>
                    <Add />
                </Button>
            <Divider />
            <Grid className="exerciseContent" >
            {exercises.map(exercise => (
                <Card>
                    <tr key={exercise.id}>
                <List>
                    <ListItem
                        key={exercise.id}
                        secondaryAction={
                            <IconButton onClick={handleClickOpen}>
                                <Delete />
                            </IconButton>
                        }>
                        <Button 
                        sx={{mr:4}}
                        href={(`/exercises/edit/${exercise.id}`)} >
                            <Edit />
                        </Button>
                        <ListItemText sx={{justifyContent:'center', width:'400px'}}
                            primary={exercise.exercise_name}
                            secondary={showCategories ? exercise["exerciseCategories.category_name"] : null}
                        />
                    </ListItem>
                    <Dialog
                        open={open}
                        onClose={handleClose}
                        style={{ borderColor: 'red' }}
                    >
                        <Box sx={{ borderTop: 3, color: 'red' }}>
                            <DialogTitle sx={{ color: 'black', backgroundColor: 'gainsboro', pl: 11 }}>
                                Delete Exercise
                            </DialogTitle>
                            <DialogContent>
                                <DialogContentText color='black' >
                                    <Warning fontSize='large' color='error' id='warning' />
                                    Are you sure you want to delete the exercise: {exercise.exercise_name} ?
                                </DialogContentText>
                            </DialogContent>
                            <DialogActions >
                                <Button variant='contained' onClick={() => deleteExercise(exercise.id)} autoFocus>
                                    Yes
                                </Button>
                                <Button variant='outlined' onClick={handleClose}>No</Button>
                            </DialogActions>
                        </Box>
                    </Dialog>
                </List>
                </tr>
                </Card>
            ))}
            </Grid>
        </Card>
    </Grid>
)

}

export default Exercises

My delete function

useFormExercises.js

...
    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    }

    const deleteExercise = async (id) => {
        try {
            await fetch(`${BASE_URL}/exercises/${id}`, {
                method: "DELETE",
            }).then(response => {
                setExercises(exercises.filter(exercise => exercise.id !== id))
                return response.json()
            })
        } catch (error) {
            console.log(error)
        }
    }

And if another thing seems of, please share your opinion!
Thanks in advance!

How to check redundancy in for loop

I am pulling some information from an API and one of my fields may or may not have duplicate content. How do I identify the redundancy and not print it on the screen if it’s a duplicate?

Here’s my loop, and “Description” is the field that sometimes has the same content as its previous sibling:

for (i = 0; i < data.length; i++) {
    htmlString += '<li><h3 class="session-item">' + data[i].Title + '</h3>';
    htmlString += '<p class="session-description">' + data[i].Description + '</p></li>';
}

Is this something I should check/compare with the previous sibling or is there a better way?

I tried a simple comparison but this didn’t work:

var tempDesc = document.getElementsByClassName('session-description');
for (i = 0; i < data.length; i++) {
    htmlString += '<li><h3 class="session-item">' + data[i].Title + '</h3>';
    if(tempDesc === data[i].Description) {
        htmlString += '</li>';
    } esle {
        htmlString += '<p class="session-description">' + data[i].Description + '</p></li>';
    }
}

Uncaught TypeError: Cannot read properties of null (reading ‘original’)

When creating a simple training project, an error flies into me.

Uncaught TypeError: Cannot read properties of null (reading 'original')
    at Character (Character.js:7:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at mountIndeterminateComponent (react-dom.development.js:20913:1)
    at beginWork (react-dom.development.js:22416:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)
    at beginWork$1 (react-dom.development.js:27405:1)
    at performUnitOfWork (react-dom.development.js:26513:1)
    at workLoopSync (react-dom.development.js:26422:1)

Moreover, if you quickly refresh the page, you can see the images with which the error occurs, and links to the images are working.

Fake API when I took date

https://api.tvmaze.com/characters/1

App.js

import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import Character from "./components/Character";

function App() {
  const [characters, setCharacters] = useState([]);

  useEffect(() => {
    for (let i = 1; i <= 100; i++) {
      characterFetch(i);
    }
  }, []);

  async function characterFetch(id) {
    fetch("https://api.tvmaze.com/characters/" + id)
      .then((response) => response.json())
      .then((json) =>
        setCharacters((lastcharacters) => [...lastcharacters, json])
      );
  }

  return (
    <div className="App">
      {characters.map((character) => {
        return <Character character={character} key={character.id} />;
      })}
    </div>
  );
}

export default App;

Character.js

import React from "react";

const Character = (props) => {
  if (props.character.name !== "Not Found") {
    var construct = (
      <>
        <img src={props.character.image.original} alt="Character_photo" />  //error
        <div> {props.character.id} </div>
        <div>{props.character.name}</div>
      </>
    );
  }
  return <div>{construct}</div>;
};

export default Character;

How do I find the maximum depth of a particular property value in an array of objects of unknown depth in javascript?

I have an array of objects of unknown depth as follows:

[
    {
        "Application": "noun",
        "Dependencies": [
            {
                "Application": "ant"
            },
            {
                "Application": "ball"
            },
            {
                "Application": "cat"
            },
            {
                "Application": "dog"
            },
            {
                "Application": "insect",
                "Dependencies": [
                    {
                        "Application": "cat"
                    },
                    {
                        "Application": "lion"
                    }
                ]
            },
            {
                "Application": "goat"
            },
            {
                "Application": "horse"
            },
            {
                "Application": "insect",
                "Dependencies": {
                    "Application": "ant"
                }
            },
            {
                "Application": "jaguar"
            },
            {
                "Application": "kite"
            },
            {
                "Application": "lion"
            },
            {
                "Application": "monkey",
                "Dependencies": {
                    "Application": "dog",
                    "Dependencies": [
                        {
                            "Application": "ant",
                            "Dependencies": [
                                {
                                    "Application": "bell"
                                },
                                {
                                    "Application": "boar"
                                },
                                {
                                    "Application": "king",
                                    "Dependencies": {
                                        "Application": "lion"
                                    }
                                },
                                {
                                    "Application": "pig"
                                },
                                {
                                    "Application": "skunk",
                                    "Dependencies": [
                                        {
                                            "Application": "cat"
                                        },
                                        {
                                            "Application": "rat"
                                        },
                                        {
                                            "Application": "boar",
                                            "Dependencies": {
                                                "Application": "dog",
                                                "Dependencies": [
                                                    {
                                                        "Application": "apple",
                                                        "Dependencies": [
                                                            {
                                                                "Application": "tree"
                                                            },
                                                            {
                                                                "Application": "lion"
                                                            }
                                                        ]
                                                    },
                                                    {
                                                        "Application": "animal",
                                                        "Dependencies": [
                                                            {
                                                                "Application": "rat"
                                                            },
                                                            {
                                                                "Application": "boar"
                                                            },
                                                            {
                                                                "Application": "kite"
                                                            }
                                                        ]
                                                    }
                                                ]
                                            }
                                        },
                                        {
                                            "Application": "ball"
                                        },
                                        {
                                            "Application": "rat"
                                        }
                                    ]
                                },
                                {
                                    "Application": "nice"
                                },
                                {
                                    "Application": "soap"
                                },
                                {
                                    "Application": "new",
                                    "Dependencies": [
                                        {
                                            "Application": "cot"
                                        },
                                        {
                                            "Application": "bed"
                                        }
                                    ]
                                },
                                {
                                    "Application": "house"
                                }
                            ]
                        },
                        {
                            "Application": "things",
                            "Dependencies": [
                                {
                                    "Application": "dress"
                                },
                                {
                                    "Application": "pant"
                                },
                                {
                                    "Application": "shoe"
                                },
                                {
                                    "Application": "tie"
                                },
                                {
                                    "Application": "shirt"
                                }
                            ]
                        }
                    ]
                }
            }
        ]
    },
    {
        "Application": "pronoun",
        "Dependencies": [
            {
                "Application": "ant"
            },
            {
                "Application": "cat"
            },
            {
                "Application": "dog"
            },
            {
                "Application": "lion"
            },
            {
                "Application": "insect"
            }
        ]
    }
]

I need to find the maximum depth of the property values like ant, ball, cat etc. in the array of objects.
In the above array of objects, I have two objects namely noun and pronoun. I need to find the maximum depth of each property value in the noun and pronoun objects.
For example, if we take "Application": "noun" as level 1, then the value ant occurs first at level 2, then at level 3 and lastly at level 4 in the noun object. So, the maximum depth of ant in the noun object is 4. Similarly, the same ant value occurs at level 2 in the pronoun object. So, the maximum depth of ant in pronoun object is 2. This way, I need to find the maximum depth of all the values(ant,ball,cat,dog,insect,lion etc etc).

The desired output should be as follows:

[
    {
        "value": "ant",
        "enrichment": {
            "applicationTier": "noun:4, pronoun:2, default:4"
        },
        "attribute": "application_tier"
    },
    {
        "value": "ball",
        "enrichment": {
            "applicationTier": "noun:6, default:6"
        },
        "attribute": "application_tier"
    },
    {
        "value": "cat",
        "enrichment": {
            "applicationTier": "noun:5, pronoun:2, default:5"
        },
        "attribute": "application_tier"
    },
    {
        "value": "dog",
        "enrichment": {
            "applicationTier": "noun:7, pronoun:2, default:7"
        },
        "attribute": "application_tier"
    },
    {
        "value": "insect",
        "enrichment": {
            "applicationTier": "noun:2, pronoun:2, default:2"
        },
        "attribute": "application_tier"
    },
    {
        "value": "lion",
        "enrichment": {
            "applicationTier": "noun:9, pronoun:2, default:9"
        },
        "attribute": "application_tier"
    }
]

In the above output, the enrichment object indicates the maximum depth of the properties in the noun and pronoun objects. Here, default is the maximum depth among the noun and pronoun depths. The only thing is that the output should be exactly like the above output. Please help.

Dropdown Menu issue reactjs console i see “right” property of “DropdownMenu” has been deprecated. Please use “end” instead. react version of 18.1.0

import React from 'react';
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
  UncontrolledDropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem } from 'reactstrap';

export default class Navi extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }
  render() {
    return (
      <div>
        <Navbar color="light" light expand="md">
          <NavbarBrand href="/">reactstrap</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
            <Nav className="ml-auto" navbar>
              <NavItem>
                <NavLink href="/components/">Components</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="https://github.com/reactstrap/reactstrap">GitHub</NavLink>
              </NavItem>
              <UncontrolledDropdown nav inNavbar>
                <DropdownToggle nav caret>
                  Options
                </DropdownToggle>
        

in here i see the problem i dont have any idea how i must solve the problem. Just down below it says a problem to use “right” keyword.In the console it says “right” property of “DropdownMenu” has been deprecated.
Please use “end” instead. for the dropdownMenu right section

                <DropdownMenu right>
                  <DropdownItem>
                    Option 1
                  </DropdownItem>
                  <DropdownItem>
                    Option 2
                  </DropdownItem>
                  <DropdownItem divider />
                  <DropdownItem>
                    Reset
                  </DropdownItem>
                </DropdownMenu>
              </UncontrolledDropdown>
            </Nav>
          </Collapse>
        </Navbar>
      </div>
    );
  }
}

How to upload files with Axios / Vue with to Django REST API backend

I have both Vue frontend / Django REST API backend repository setup below.
I am struggling to find a way to send the file to the Django backend.

Django backend
https://github.com/TraitOtaku/Vue-File-Upload

Vue frontend
https://github.com/TraitOtaku/Django-Rest-API-for-Fileupload

I was able to confirm that I can upload the files with the Django API interface(image below)
Django API interface

and also using the postman desktop app.

My specific problem here is that when the user selects the file, I don’t know how to attach the file data to the POST request.

In the Vue repo, there is an App.vue and form inside the vue file.

<template>
  <div class="container mt-5">
    formState:{{ formState }}
    <form enctype="multipart/form-data">
      <div class="form-group my-2">
        <label for="exampleInputEmail1">File Name</label>
        <input class="form-control" v-model="formState.name">
      </div>

      <div class="form-group my-2">
        <label class="form-label" for="customFile">Upload Store Documents</label>
        <input type="file" class="form-control" id="storeFile"
          @change="appendFile(event.target.name, event.target.files)" />
      </div>

      <button type="submit" class="btn btn-primary" @click.prevent="createStoreDoc">Submit</button>
    </form>

    <h1>Store Documents</h1>
    <div v-if="storeDoc">
      <div v-for="doc in storeDoc" :key="doc.id">
        <div>
          File ID:{{ doc.id }}
        </div>
        <div>
          File Name:{{ doc.name }}
        </div>
        <div>
          File Content:{{ doc.file }}
        </div>
        <hr>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, toRaw, reactive } from "vue";

const formState = reactive({
  name: "",
  file: null,
});


const apiClient = axios.create({
  baseURL: "http://127.0.0.1:8000/api/store-doc/",
  withCredentials: false,
  headers: {
    // Accept: "application/json",
    "Content-Type": "application/json",
  },
});

const storeDoc = ref(null)
const getStoreDoc = () => {
  apiClient.get()
    .then((response) => {
      storeDoc.value = response.data
      // console.log(storeDoc)
    })
}
getStoreDoc()


const createStoreDoc = () => {
  apiClient.post('', toRaw(formState))
    .then((response) => {
      console.log("success!" + response.data);
      getStoreDoc()
    })
    .catch((error) => {
      console.log(error);
    });
}



</script>


I have this POST request createStoreDoc() and this will work but won’t attach file to the request yet.

I want to achieve this with or composition API, not Options API.
Please feel free to fork the repo to answer this question.

Thank you for reading and lending your knowledge.

How do you set node flags for a npm run-script? [duplicate]

There is a Node.js flag that increases the length of stack traces:

--stack-trace-limit (number of stack frames to capture)
     type: int  default: 10

But I am running my command like this from a package.json:

  "scripts": {
    "unit-test": "jasmine"
  }

This is not an NPM flag, or a Jasmine flag either. It’s a flag for the node command.

How do can I set --stack-trace-limit when I npm run unit-test?