Reactjs – Can’t call setState on a component that is not yet mounted

I am getting an error can’t call setState on a component that is not yet mounted.
Weirdly the Udemy video i am following does not get this error. I tried to check if this is due to v5 and v6 routing issue but found no solutions.
What I am trying to do here is to pull specific user data when i click on a profile name or search a username. Current View But the results are not showing for every this.state calls

import React,{Component} from "react";
import withRouter from '../withRouter';
import Repose from "./Repose";
class Specific extends Component{
    constructor(props){
        super(props);
        this.state ={ user:[]};
        const FetchUser = async(user)=>{
            const API_Call=await fetch(`https://api.github.com/search/users/${user}`)
            const data= await API_Call.json();
            return {data}
        }
        FetchUser(props.params.login).then((res)=>{
            if(!res.data.message){
                this.setState({user:res.data})
            }
        })
    }
    
    Data () {
        if(this.state.user.login===0){
            return(<i>No user with given username{this.props.params.login}</i>)
        }else {
            return(
                <center>
  <section className="Specific">
    <div className="main" id="main">
    <div className="container">
      <div className="row">
      <div className="col-lg-12 col-md-12">
        <div className="SUsersData">
        <i className="fas fa-heart  NotFave"></i><h4>Name :<i className="bl">{this.state.user.name}</i>   </h4>
        <img src={this.state.user.avatar_url}alt="" />
          <h4>followers :<i className="bl"> {this.state.user.followers} </i>  </h4> 
          <h4>location :<i className="bl"> {this.state.user.location} </i> </h4>
          <Repose user={this.props.params.login}/>

        </div>
        </div>
      </div>
    </div>
    </div>
    
  </section>
</center>
            );
        }
    }

    render(){
        return(
            <React.Fragment>
                {this.Data()}
            </React.Fragment>
        );
    }
}

export default withRouter(Specific);

Multi-step form won’t go to next section JS/HTML

So I wrote this multi-step form and it worked with the current code I have listed below until I changed it to send/receive data from php. The only thing that works is updating the progress bar but other then that it doesn’t work. I have an idea why its not working cause of the actual button event isn’t targeting the correct $(this).parent(); when I changed it from nextSection() to onSubmit(). I would possibly like to write it where it just selects the div class from an object then remove the current section but I wanna keep it the way I have for now.

    $(".btn").on("click", nextSection);

    function nextSection() {
    if (typeof sections[current] !== "undefined") {
        if(valid) {
            current_section = $(this).parent();
            next_section = $(this).parent().next();
            console.log(current_section)
            next_section.fadeIn();
            current_section.remove();
            current++;
            updateProgressbar();
            if (current === 1) {
                let username = $(".username").val();

                updatePenguinObj("username", username);
            } else if (current === 2) {
                let password = $(".password").val();
                let email = $(".email").val();

                updatePenguinObj("password", password);
                updatePenguinObj("email", email);
            } else if (current === 3) {
                let name = $(".done");
                name.text(name.text().replace(/%.+?%/, userData.username));
            }
        }
    }
}

Then I changed it to the onSubmit() function w/ the validation responses.

$(".btn").on("click", onSubmit);

function onSubmit(event) {
    event.preventDefault()

    let request = new XMLHttpRequest()

    request.onreadystatechange = () => handleResponse(request)

    let formData = new FormData()
    formData.append('username', userData.username);
    formData.append('color', userData.colorId);
    formData.append('password', userData.password);
    formData.append('email', userData.email);

    request.open('POST', 'scripts/php/create.php')
    request.send(formData)
}

function handleResponse(request) {
    if (request.readyState !== XMLHttpRequest.DONE || request.status !== 200) {
        return
    }

    let response = JSON.parse(request.responseText);

    if (!response) {
        return
    }
    
    sectionValidation(response);
}
function sectionValidation(response) {
    valid = true;
    let section = $(sections[current]);
    let input = section.find("input");
    input.each(function() {
        let inputs = $(this).attr('type') === "checkbox" ? !$(this).is(':checked') : input;
        if(inputs) {
            if (!response.valid) {
                showError(response.message);
                return valid = response.valid;
            }
        }
    });
    if(valid) {
        nextSection(); //This is where nextSection is excuted to go to next page but doesnt.
    }
}

I pastebin the entire code for each file type that way im not spamming this thread with just code. Overall i’m just trying to figure out how to fix it where I can go to the next section.

HTML – https://pastebin.com/eF8eXBfN
JS – https://pastebin.com/LuvYtYFc
PHP –
Basically just returns a JSON Object {message: "Test", valid: false} for the message responses and validation for it to go to next section.

Is there implicit function currying here?

https://codepen.io/markvital/pen/vYNZXgW

function handleDrag(delta){setDelta(delta);}

We see this being called inside the onDrag props. Then we do:

onDrag={handleDrag}

To call the function whenever we drag something, but then we pass the handleDrag and it somehow calls this method:

onDrag={ (e, data) => { onDrag({x: data.x, y: data.y }, id) } }

There seems to be an implicit handleDrag(delta)(e, data) currying done, but I am not sure what data is coming from. The documentation doesn’t say anything about where the data comes.

https://github.com/react-grid-layout/react-draggable#draggable-api

REACTJS: Changing variable value inside useEffect() ore accessing the that appears in useEffect()

I am creating a submit-form and I am using useEffect() here.

useEffect receives a 400-Statuscode and an error message from my backend and I want to show that Error on my Submit-Form, but I am struggling to access this error outside the ‘useEffect(()=>{}’ – Scope.

this is my code (I am using react-bootstrap and @redux-toolkid):

Short version:

var error = null

useEffect(() => {
console.log('useEffect(): ')
console.log(createResult)
if (createResult.isSuccess) {
createResult.reset()
        dispatch(hideCreateMessageDialog())
    }
    if (createResult.error) {
        error = createResult.error


console.log(error) //output = null

I have also tried to use a return(error)statement, but that lets my whole application crash. I also tried to use error as parameter like useEffect(error)()=>...

Why can’t I access the error-variable within the useEffect()-scope??
I need to use the error-message in my JSX-Code
.

How can I do this?

value of createResult.error:

{
    "status": 400,
    "data": {
        "Error": "Could not create forum message. Reason: Forum thread ID is missing"
    }
}


complete code bellow


import React, { useEffect } from 'react'

// utils
import { jlog, jsn } from '../../../utils/parseJSON'
import JsonHelper from '../../../utils/parseJSON'

//bootstrap
import Button from 'react-bootstrap/Button'
import FloatingLabel from 'react-bootstrap/FloatingLabel'
import Form from 'react-bootstrap/Form'
import Modal from 'react-bootstrap/Modal'
import Spinner from 'react-bootstrap/Spinner'
import Stack from 'react-bootstrap/Stack'

//redux
import { useDispatch, useSelector } from 'react-redux'

// import selectors
import { selectCreateMessageDialog, selectHandleThreadID, selectHandleThreadName } from '../../../redux/ui/UISlices'

//import my reducers
import { useCreateMessageMutation } from '../../../redux/forum/ForumMessageSlice'
import { hideCreateMessageDialog } from '../../../redux/ui/UISlices'

export default function CreateMessageDialog() {
    var error = null
    const [createMessage, createResult] = useCreateMessageMutation()
    const dispatch = useDispatch()
    const parentThreadID = useSelector(selectHandleThreadID)
    const parentThreadName = useSelector(selectHandleThreadName)
    const handleSubmit = function (event) {
        event.preventDefault()
        const newMessage = {
            title: event.target.elements.ForumMessageTitleInput.value,
            text: event.target.elements.ForumMessageTextInput.value,
            threadID: parentThreadID
        }
        createMessage(newMessage)
    }

    useEffect(() => {
        console.log('useEffect(): ')
        console.log(createResult)
        if (createResult.isSuccess) {
            createResult.reset()
            dispatch(hideCreateMessageDialog())
        }
        if (createResult.error) {
            error = createResult.error
            console.log('error in createResult: ')
            console.log(jsn(error))
            console.log(jsn(error.data.message))
            console.log(jsn(error.status))
        }
    })

    return (
        <>
            <Modal show={useSelector(selectCreateMessageDialog)} onHide={() => dispatch(hideCreateMessageDialog())}>
                <Modal.Header closeButton>
                    <Modal.Title>{JSON.stringify(error)}</Modal.Title>
                </Modal.Header>
                <Form onSubmit={handleSubmit}>
                    <CreateMessageBody error={error} threadID={parentThreadID} threadName={parentThreadName} />
                    <Modal.Footer>
                        <Button
                            variant='secondary'
                            id='CancelCreateForumMessageButton'
                            onClick={() => dispatch(hideCreateMessageDialog())}
                        >
                            Cancel
                        </Button>
                        <Button type='submit' variant='primary' id='CreateForumMessageButton'>
                            Create Message
                        </Button>
                    </Modal.Footer>
                </Form>
            </Modal>
        </>
    )
}

function CreateMessageAlert({ error }) {
    return <JsonHelper data={error} />
    /* if (error) return error.data */
    return null
}

function CreateMessageBody(props) {
    console.log('props von CreateMessageBody: ' + jsn(props))
    if (false) {
        return (
            <Modal.Body>
                <Spinner animation='border' role='status'>
                    <span className='visually-hidden'>Loading...</span>
                </Spinner>
            </Modal.Body>
        )
    }

    

    return (
        <Modal.Body>
            <Stack>
                <JsonHelper data={props} />
                <CreateMessageAlert error={props} />
                <FloatingLabel controlId='ForumMessageTitleInput' label='Message Title' className='mb-3'>
                    <Form.Control type='text' name='ForumMessageTitleInput' placeholder='Eigener Title' />
                </FloatingLabel>

                <FloatingLabel controlId='ForumMessageTextInput' label='Message' className='mb-3'>
                    <Form.Control
                        as='textarea'
                        type='text'
                        name='ForumMessageTextInput'
                        placeholder='Message'
                        style={{ height: '125px' }}
                    />
                </FloatingLabel>
            </Stack>
        </Modal.Body>
    )
}

Any ideas how I can add the picklist to the following JS

The following creates a dropdown picklist and a comment box, the picklist is empty and I cant figure out where to put the options inside the script

<script>
$(document).ready(function(){
    var withdrawalCharLimit = 600;
    buildWithdrawalDropdown();
    $("#withdrawalCharRemainingGWU").text(withdrawalCharLimit-$("#withdrawalCommentsGWU").val().length);
   
    $("#withdrawalReasonGWU").change(function() {
        if($("#withdrawalCommentsGWU").val()==""){
            $("#taComments").val($("#withdrawalReasonGWU").val());
        } else {
            $("#taComments").val($("#withdrawalReasonGWU").val()+". Detail: "+$("#withdrawalCommentsGWU").val());
        }
    });
    $("#withdrawalCommentsGWU").keyup(function(){
        if($("#withdrawalCommentsGWU").val()==""){
            $("#taComments").val($("#withdrawalReasonGWU").val());
        } else {
            $("#taComments").val($("#withdrawalReasonGWU").val()+". Detail: "+$("#withdrawalCommentsGWU").val());
        }
        $("#withdrawalCharRemainingGWU").text(withdrawalCharLimit-$("#withdrawalCommentsGWU").val().length);
    });
   
});
 
function buildWithdrawalDropdown(){
    var withdrawalSelect = $("<select class='form-control' id='withdrawalReasonGWU'></select>").insertBefore("#taComments");
    var withdrawalComments = $("<label for='withdrawalCommentsGWU'>Additional Comments (optional):</label><textarea maxlength='600' class='form-control' id='withdrawalCommentsGWU'>")}
    </script>

The list looked like this
how the options should load

Do something after promises looping through an array and fulfilling, react javascript

Most of the other questions don’t account for doing something after Promises.all. Also, my situation might be strange.

Promise.all still lets the below run multiple times. But I only want doSomethingWithResults(results) to happen once all iterations are finished.

I am forced to use a promises here so I need to find a solution to “awaiting” all promises to finish.

const [results, setResults] = useState([])

const handleSubmit = (e) => {
    e.preventDefault();
    const promises = [];

    stuff.map((thing) => {
      const uploadTask = digitaloceantask.something(thing)
      promises.push(uploadTask);
      uploadTask.on(
        "state_changed",
         () => {
          storage()
            .ref("something")
            .child(something.name)
            .getDownloadURL() // 2 images
            .then((result) => {
              setResults((prevState) => [...prevState, result]);
            });
        }
      );
      const result = Promise.all(promises)
     }
      doSomethingWithResults(results) // This happens multiple times, instead of waiting for all promises to finish. Would an if statement help?
})

can we control mat-drawer toggle speed?

Here’s my code, I am just a beginner in the front-end world so please help me out to solve my delay issue in opening and closing the sidebar.

<mat-drawer-container autosize>
  <mat-drawer #drawer mode="side" [opened]="isShowing" (mouseout)="toggle()">
    <mat-nav-list>
      <div>
        <div>
          <a mat-list-item class="panel-list-item">
            Marketplace
          </a>
        </div>
      </div>
    </mat-nav-list>
  </mat-drawer>
  </mat-drawer-container>

Javascript indexOf not defined

I’m working on a simple web app that essentially allows a guitarist to convert chords based on the positions of their capo – you don’t really have to know what that means, but might help if you do lol. I’ve made it work for an entry of a single chord, but I want the user to be able to enter multiple chords to transpose, so the goal is for them to enter multiple chords which will be stored in an array. From there, I have a preset array of characters for each possible chord, and I have written a nested loop function to search through the array of possible chords so that they can return the index number of that possible chord.

let chordShapes = ["E", "F", "F# / Gb", "G", "G# / Ab", "A", "A# / Bb",
                     "B", "C", "C# / Db", "D", "D# / Eb"];

For example, the user inputs the chords A and E, which will be entered into an array called inpArr. From there, I want the function to return the index of the matching chords in an array called inputChords, so in this case that new array should be [5,0] after this function, and from there I should be able to finish this up. However, I am getting the error that says indexOf is not defined in the function. Here is the function along with the relevant arrays:

let inputChords = ["A", "E"];

function findNums(inpArr){
    let newArr = [];
    for(let i=0; i<inpArr.length-1; i++){
        for(let j=0; j<chordShapes.length-1; j++){
            if(inpArr[i]==chordShapes[j]){
                newArr[i] = indexOf(chordShapes[j]);
                console.log(`inputNum: ${newArr[i]}`); 
            }
        }
    return newArr;
    }
};

findNums(inputChords);

I see from other answers that the discrepancy might be because indexOf is used for strings and arrays (I know strings are a type of array), but this is definitely both of those. All the other questions I’ve seen about this seem to be about programs above my expertise so I am not sure how to apply their solutions to my own problem here.
Any help would be appreciated 🙂

Should toggle navigation be abandoned altogether in 2022?

Synopsis

I’ve been researching what is considered “best practice“ for site header/navigation with submenus or hidden content that is toggled between visibility. Frankly, I think most websites have at the very least some version of toggled navigation for browsers at a mobile size.

I’ve noticed a growing opinion in threads and articles that all site navigation should function without JavaScript. While <1% of users are disabling JavaScript in their browser, it’s theorized to be much higher for users who disable JavaScript on a site-by-site basis. The primary reasons for disabling are: the old myth that JavaScript is insecure; plugins that filter and disable some JavaScript like Ad Blocker; or users trying to bypass paywalls (I’ve seen a ton of videos on TikTok showing how to disable JavaScript to bypass a paywall).

This means any navigation with toggled content would have to be achieved with pure CSS.

Desktop Approaches for Submenus

(CSS) The Old Checkbox Hack

This is an old one (and more widely browser supported). It uses an input checkbox’s :checked state to toggle content between visibility. The actual input is usually hidden and the label is styled to be the toggle. Here’s the very basic setup:

<!-- HTML -->
<input type="checkbox" id="toggle" class="input-toggle">
<label for="input-toggle">Menu Item</label>
<ul class="submenu">
    <li>Submenu Item 1</li>
    <li>Submenu Item 2</li>
</ul>
/* CSS */
.input-toggle {
    visibility: hidden;
    margin-top: -999px;
}

.submenu {
    display: none;
}

.input-toggle:checked ~ .submenu {
    display: block;
}

This approach only works if there is one toggle. If there are multiple siblings with toggle inputs, it will open and close all of them. However, an easy solution would be to just use a different CSS combinator and add some JavaScript so multiple checkboxes aren’t checked at once. (I used jQuery, sorry.)

<!-- HTML -->
<input type="checkbox" id="toggle" class="input-toggle">
<label for="input-toggle">Menu Item 1</label>
<ul class="submenu">
    <li>Submenu Item 1</li>
    <li>Submenu Item 2</li>
</ul>
<input type="checkbox" id="toggle" class="input-toggle">
<label for="input-toggle">Menu Item 2</label>
<ul class="submenu">
    <li>Submenu Item 1</li>
    <li>Submenu Item 2</li>
</ul>
<input type="checkbox" id="toggle" class="input-toggle">
<label for="input-toggle">Menu Item 3</label>
<ul class="submenu">
    <li>Submenu Item 1</li>
    <li>Submenu Item 2</li>
</ul>
/* CSS */
.input-toggle {
    visibility: hidden;
    margin-top: -999px;
}

.submenu {
    display: none;
}

.input-toggle:checked + label + .submenu {
    display: block;
}
// jQuery
$(".input-toggle").change(function () {
    $(".input-toggle").not(this).prop('checked', false);
});

Yes, we’re already back to using JavaScript. However, if a user has disabled JavaScript then the navigation would still open the submenus—they would just have the added frustration of opening and closing each of the submenus manually. This approach would only work if none of the submenus overlap or completely hide another submenu. We could try using radio inputs instead, but then one portion of the menu would always be open without additional JavaScript

Support

You may be wondering why would I consider this approach first over :focus-within. The :checked state is more widely supported.

The Challenges

  1. It can only meet accessibility guidelines by using JavaScript and aria labels to add keyboard functionality because the input tag is only meant to be used inside of a form.
  2. If a user has JavaScript disabled for any reason, then it won’t meet accessibility guidelines.
  3. It’s not semantic HTML. This isn’t the intended use for the input tag.

(CSS) Using :focus-within

A bit more of a recent approach. This approach uses :focus-within to toggle content. Here are three examples of how it’s been used:

  1. https://codepen.io/dannievinther/pen/NvZjvz
  2. https://codepen.io/scottohara/pen/ybjPEx
  3. https://codepen.io/una/pen/pVvXmK

Support

This approach is slightly less supported.

The Challenges

  1. Once again, it can only meet accessibility guidelines by using JavaScript and aria labels to add keyboard functionality.
  2. If a user has JavaScript disabled for any reason, then it won’t meet accessibility guidelines.
  3. It at least gives us semantic HTML and the hack is in the CSS.

(JavaScript) Just use JavaScript

I’ve seen a lot of suggestions to just keep top-level links in the top navigation. If a user has JavaScript disabled, then they can still navigate the site by the top links. However, this approach has also been shown to be confusing to users—especially with mixed navigation. It would also only work if the submenus show on hover, which tbh isn’t my favorite. I would rather the user have to click on the top menu label to open the submenu.

Mobile Approach For Just A Menu

Almost every site I visit at a mobile size has a side shelf menu… and they’re not functioning without JavaScript. The CSS approaches above could be tailored for sites at a mobile size, but they’ll still have their challenges.

Conclusion

If I’m to truly develop JavaScript-free navigation, then it seems to me that the best practice would be to just have a simple menu with top links—the pages could then have sub navigation links at the top (though now users are having to click and wait.) At a mobile size, I guess I could possibly have the menu links at the top under the site logo with scroll overflow?… I haven’t even really stopped to think about what the user experience on mobile would be like with a setup like that.

I could really use some help and insight into how I should be developing navigation. Is it still ok to use JavaScript?

Updating parent form with a select2 field when closing another modal form django

I am trying to add this functionality to my django app. I have a select2 field as a ForeignKey data type field in my main form. Now, I also got an “add” button right next to it that when clicked, opens a modal with another form. That form creates another instance for the select2 to look for, another entry, so that’s good and settled. But, I want it to, when submitting the form in the modal, instead of the main form page being refreshed and having to refill all other fields again, it automatically selects the instance it has just created on the select2 field. I am fairly new to the front-end aspect of it all so it would be great to have some guidance.

Parallel for loops in p5js

I was wondering if it is possible to run parallel for loops in JavaScript using the p5js library?

I am trying to speed up the following code and run multiple points in parallel given each is independent.

for (ix = 0; ix < QSS; ix++) {
    for (iy = 0; iy < QSS; iy++) {

        st1 = 8 * Perlin((ix + xspeed * Tme) / 400 * xs * P2, (iy + yspeed * Tme) / 400 * xs * P2, Tme);
        dst1 = Perlin((ix + xspeed * Tme) / 40 * xs * P2, (iy + yspeed * Tme) / 40 * xs * P2, Tme);
        nss1 = Perlin((ix + xspeed * Tme) / 100 * xs * P2, (iy + yspeed * Tme) / 100 * xs * P2, st1 + dst1, Tme);
        st2 = 8 * Perlin((ix + xspeed * Tme) / 800 * xs * P2, (iy + yspeed * Tme) / 800 * xs * P2, Tme);

    }
}

Perlin is a modified version of the p5js noise function. This seems embarrassingly parallel to me and would be easily possible in a different language, I am just wondering if there is any possible way in JavaScript. Many thanks in advance.

Trying to create an edit function, Hitting brick wall

As the title says. I’m trying to create an edit function in my VehiclesController.

I think I’m almost there but cant pull it all together properly, Im still learning Laravel and only a few weeks in.

Routes
// Vehicle Database Routes

    Route::get('vehicles/', 'VehiclesController@index')->name('vehicles.index');
    Route::post('vehicles/', 'VehiclesController@store')->name('vehicles.store');
    Route::post('vehicles/destroy', 'VehiclesController@destroy')->name('vehicles.destroy');
    Route::patch('vehicles/edit/{id}/', 'VehiclesController@edit')->name('vehicles.edit');

This is my VehiclesController

namespace AppHttpControllers;

use AppVehicle;
use CarbonCarbon;
use IlluminateHttpRequest;
use IlluminateFacadesStorage;

class VehiclesController extends Controller
{
    /**
     * Display a dynamic datatable of the vehicles with
     * pagination and full search and sorting.
     *
     * @return IlluminateHttpResponse
     */
    public static function index()
    {
        $vehicles = Vehicle::all();
        return view('vehicles.index', $vehicles)->with(compact('vehicles'));
    }

    /**
     * Store a newly created vehicle in datatbase.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        // Getting values from the blade template form.
        $vehicle = new Vehicle;
        $vehicle->manufacturer = $request->manufacturer;
        $vehicle->model_name = $request->model_name;
        $vehicle->version = $request->version;
        $vehicle->powertrain = $request->powertrain;
        $vehicle->trans = $request->trans;
        $vehicle->fuel = $request->fuel;
        $vehicle->model_year = $request->model_year;
        $vehicle->updated_at = now(); //Carbon now
        $vehicle->man_logo = strtolower($request->manufacturer) . '.png';
        //Save new vehicle to database
        $vehicle->save();

        return back();
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppVehicle  $vehicle
     * @return IlluminateHttpResponse
     */
    public function edit(Vehicle $vehicle, $id)
    {
        //Get the data from the database
        $id = Vehicle::findOrFail('id');

        return view('vehicles.index', $id)->with(compact('id'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppVehicle  $vehicle
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Vehicle $vehicle)
    {
        //
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  AppVehicle  $vehicle
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        $vehicle = Vehicle::find($id);
        $vehicle->delete();

        return redirect('/vehicles')->with('success', 'Vehicle removed.');
    }
}

This is the script from my app.blade.

<script>
        $(function() {
            // Edit Vehicle
            $("#edit_vehicle_form").submit(function(e) {
                e.preventDefault();
                const fd = new FormData(this);
                $("#edit_vehicle_btn").text("Processing...");
                $.ajax({
                    url: '{{ route('vehicles.edit', id) }}',
                    method: 'PATCH',
                    data: fd,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res) {
                            Swal.fire( /*Sweet Alert */
                                'Edit Vehicle'
                                'Successfully updated.',
                                'success'
                            )

                        }
                        $("#editVehicleModal").modal('hide');
                        console.log(res); /* For debugging raw data */
                    }
                });
            });
        });
    </script>

This is my ‘~/views/vehicles/index.blade.php’ which contains my DataTable with my store( ) & edit( ) functions.

@extends ('layouts.app')

@section('content')
    {{-- add new vehicle modal start --}}
    <div class="modal fade" id="addVehicleModal" tabindex="-1" aria-labelledby="exampleModalLabel" data-bs-backdrop="static"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="exampleModalLabel">
                        Add New Vehicle
                    </h5>
                    <button type="button" class="close" data-bs-dismiss="modal">Close &#10006;
                    </button>
                </div>
                <form action="#" method="POST" id="add_vehicle_form" enctype="multipart/form-data">
                    @csrf

                    <div class="modal-body p-4 bg-light">
                        <div class="my-2">
                            <div class="col-lg">
                                <label for="manufacturer">
                                    <h5>Manufacturer</h5>
                                </label>
                                <input type="text" name="manufacturer" class="form-control" placeholder="" required />
                            </div>
                        </div>
                        <div>
                            <div class="col-lg">
                                <label for="model_name">
                                    <h5>Model</h5>
                                </label>
                                <input type="text" name="model_name" class="form-control" placeholder="" required />
                            </div>
                        </div>
                        <div class="my-2">
                            <label for="version">
                                <h5>Version</h5>
                            </label>
                            <input type="text" name="version" class="form-control" placeholder="" required />
                        </div>
                        <div class="my-2">
                            <label for="trans">
                                <h5>Transmission</h5>
                            </label>
                            <input type="text" name="trans" class="form-control" placeholder="" required />
                        </div>
                        <div class="my-2">
                            <label for="fuel">
                                <h5>Fuel Type</h5>
                            </label>
                            <input type="text" name="fuel" class="form-control" placeholder="" required />
                        </div>
                        <div class="my-2">
                            <label for="powertrain">
                                <h5>Powertrain</h5>
                            </label>
                            <input type="text" name="powertrain" class="form-control" placeholder="" required />
                        </div>
                        <div class="my-2">
                            <label for="model_year">
                                <h5>Model Year</h5>
                            </label>
                            <input name="model_year" type="number" min="1900" max="2099" step="0.25"
                                value="2020" />
                        </div>

                    </div>
                    <div class="modal-footer bg-primary">

                        <button type="submit" id="add_vehicle_btn" class="btn btn-primary">
                            Add Vehicle
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- add new vehicle modal end --}}
    {{-- edit vehicle modal start --}}
    <div class="modal fade" id="editVehicleModal" tabindex="-2" aria-labelledby="exampleModalLabel"
        data-bs-backdrop="static" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="exampleModalLabel">

                        Edit Vehicle


                    </h5>
                    <button type="button" class="close" data-bs-dismiss="modal">Close &#10006;
                    </button>
                </div>
                <form action="#" method="POST" id="edit_vehicle_form" enctype="multipart/form-data">
                    @csrf

                    <div class="modal-body p-4 bg-light">
                        <div class="my-2">
                            <div class="col-lg">
                                <label for="manufacturer">
                                    <h5>Manufacturer</h5>
                                </label>
                                <input type="text" name="manufacturer" class="form-control" placeholder="" />
                            </div>
                        </div>
                        <div>
                            <div class="col-lg">
                                <label for="model_name">
                                    <h5>Model</h5>
                                </label>
                                <input type="text" name="model_name" class="form-control" placeholder="" />
                            </div>
                        </div>
                        <div class="my-2">
                            <label for="version">
                                <h5>Version</h5>
                            </label>
                            <input type="text" name="version" class="form-control" placeholder="" />
                        </div>
                        <div class="my-2">
                            <label for="trans">
                                <h5>Transmission</h5>
                            </label>
                            <input type="text" name="trans" class="form-control" placeholder="" />
                        </div>
                        <div class="my-2">
                            <label for="fuel">
                                <h5>Fuel Type</h5>
                            </label>
                            <input type="text" name="fuel" class="form-control" placeholder="" />
                        </div>
                        <div class="my-2">
                            <label for="powertrain">
                                <h5>Powertrain</h5>
                            </label>
                            <input type="text" name="powertrain" class="form-control" placeholder="" />
                        </div>
                        <div class="my-2">
                            <label for="model_year">
                                <h5>Model Year</h5>
                            </label>
                            <input name="model_year" type="number" min="1900" max="2099" step="0.25"
                                value="2020" />
                        </div>

                    </div>
                    <div class="modal-footer bg-primary">

                        <button type="submit" id="edit_vehicle_btn" class="btn btn-primary">
                            Save Vehicle
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- edit vehicle modal end --}}
    <div class="flex-col task-header items-center mt-def mb-3 pb-4">
        <h3 class="font-normal text-xl py-4 mb-3 border-l-4 border-accent-light pl-4"><i
                class="bi bi-car-front-fill me-2"></i>

            &#160;Manage Vehicles
        </h3>
        <hr class="my-6 hr-accent">
        </hr>
        <div id="addBtn" class="card">
            <button type="button" class="button" data-bs-toggle="modal" data-bs-target="#addVehicleModal">


                <i class="bi-plus-circle me-2"></i>
                <h3 style="margin-bottom:2px;" class="p-0">&#160;Add New
                    Vehicle
                </h3>
            </button>
        </div>
    </div>


    <div class="row my-5">

        <table id="datatable" class="table dataTable" cellspacing="1px">
            <thead class="thead">
                <tr class="thead">
                    <th>Brand Logo</th>
                    <th>Make</th>
                    <th>Model</th>
                    <th>Version</th>
                    <th>Powertrain</th>
                    <th>Transmission</th>
                    <th>Model Year</th>
                    <th>Fuel</th>
                    <th>Date Added</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($vehicles as $vehicle)
                    <tr class="veh_id_{{ $vehicle->id }}">
                        <td>
                            <img id="man_logo" src="./images/manufacturers/{{ $vehicle->man_logo }}"
                                class="logo justify-content-sm-center">
                        </td>
                        <td>{{ $vehicle->manufacturer }}</td>
                        <td>{{ $vehicle->model_name }}</td>
                        <td>{{ $vehicle->version }}</td>
                        <td>{{ $vehicle->powertrain }}</td>
                        <td>{{ $vehicle->trans }}</td>
                        <td>{{ $vehicle->fuel }}</td>
                        <td>{{ $vehicle->model_year }}</td>
                        <td>{{ CarbonCarbon::parse($vehicle->updated_at)->format('d-m-Y H:i') }}</td>
                        <td>
                            <form action="{{ route('vehicles.edit', $vehicle->id) }}"> <button action="#"
                                    type="button" id="edit_vehicle_btn" data-bs-target="#editVehicleModal"
                                    data-bs-toggle="modal" class="btn btn-info">
                                    <i class="bi-pencil-square h6"></i></a>
                                </button>
                            </form>
                        </td>
                        <td>
                            <form action="{{ route('vehicles.destroy', $vehicle->id) }}" method="post">
                                @csrf
                                @method('DELETE')
                                <button type="button" class="btn btn-danger">
                                    <i class="bi-trash h6"></i>
                                </button>
                            </form>

                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
@endsection

I would like the edit function to get the vehicle instance that is clicked to populate the editVehicleModal with the current data, then update the data with an update( ) function.

javascript replace all \ with

in javascript (node) (fs module), when reading from a txt file, it converts all backslashes to double-backslashes, so that they don’t accidentally escape the characters following them.
however, having n ACTUALLY escape the character n might be desirable in some cases.
i could do something like this:

str = str.replace(/\n/g,"n").replace(/\t/g,"t")... etc

but if there’s a function that does this automatically, this is just unneccesary repetition.
i’ve done heaps of research, and still can’t find a solution to this problem