Full Calendar refetched events when react set state

I am using full calendars api as follows for fetching my events-

<FullCalendar
                ref={calendarRef}
                plugins={[listPlugin, bootstrap5Plugin]}
                initialView='listMonth'
                themeSystem='bootstrap5'
                validRange={{ "start": currentDateTime }}
                headerToolbar={{
                    start: 'listMonth prev next',
                    center: 'title',
                    end: 'Schedule',
                }}
                views={
                    {listMonth: { buttonText: 'Month' }}
                }
                eventOrder={'end'}
                customButtons={{
                    Schedule: {
                        text: 'Schedule Meeting',
                        click: function () {
                            handleCustomButtonClick();
                        }
                    }
                }}
                events={function (info, successCallback, failureCallback){
                    var startDateTime = info.start;
                    var endDateTime = info.end;

                    startDateTime.setMilliseconds(0);
                    endDateTime.setMilliseconds(0);

                    startDateTime = startDateTime.toISOString();
                    endDateTime = endDateTime.toISOString();
                    
                    startDateTime = startDateTime.substring(0, startDateTime.length - 5) + 'Z';
                    endDateTime = endDateTime.substring(0, endDateTime.length - 5) + 'Z';

                    const url = `http://localhost:8080/api/meeting/abhyasi/${props.profile.googleId}/${startDateTime}/${endDateTime}`; // Use backticks for template literals
                    const headers = new Headers();
                
                    // Add headers to the headers object
                    headers.append('X-API-KEY', ",PRGojtX9`c4e24219-fb95-;'.4ed8392hfds';");
                
                    const requestOptions = {
                        method: 'GET',
                        headers: headers
                    };
                
                    const response = fetch(url, requestOptions)
                    fetch(url, requestOptions)
                    .then(response => {
                        // check if the response is a 404
                        if (response.status === 404) {
                            // if it is, then throw an error
                            failureCallback();
                        }
                        return response.json();
                    })
                    .then(data => {
                        // Handle the JSON data here
                        console.log(data);
                        // map to events object
                        var meeting_events = data.map((meeting) => {
                            return {
                                title: meeting.meetingAgenda,
                                start: meeting.startDateTime,
                                end: meeting.endDateTime,
                                extendedProps: {
                                    startUrl: meeting.meetingStartUrl,
                                    joinUrl: meeting.meetingJoinUrl,
                                    meetingId: meeting.zoomMeetingId,
                                    meetingPassword: meeting.meetingPassword
                                }
                            }
                        });
                        successCallback(meeting_events);
                    })
                    .catch(error => {
                        // Handle any errors that occurred during the fetch
                        failureCallback(error);
                    });
                }}
                eventDidMount={
                    function(info) {

                        let start = info.event.start.toISOString();
                        let end = info.event.end.toISOString();
                        let current = new Date().toISOString();

                        if(current < end) {
                            var button = document.createElement('button');
                            button.innerHTML = 'Delete Meeting';
                            button.className = 'btn btn-primary btn-sm';
                            button.classList.add('float-end');
                            button.style.marginLeft = '10px';
                            button.style.borderRadius = '5px';
                            button.style.backgroundColor = '#dc3545';
                            button.style.borderColor = '#dc3545';
                            button.addEventListener('click', function() {
                                deleteMeeting(info.event);
                            }
                            );

                            info.el.querySelector('.fc-list-event-title').appendChild(button);
                        }

                        if(start <= current && end >= current) {
                            var button = document.createElement('button');
                            button.innerHTML = 'Start';
                            button.className = 'btn btn-primary btn-sm';
                            button.classList.add('float-end');
                            button.style.marginLeft = '10px';
                            button.style.borderRadius = '5px';
                            button.addEventListener('click', function() {
                                window.open(info.event.extendedProps.startUrl);
                            }
                            );
    
                            info.el.querySelector('.fc-list-event-title').appendChild(button);
                        }

                        if(end > current) {
                            var button = document.createElement('button');
                            button.innerHTML = 'Info';
                            button.className = 'btn btn-primary btn-sm';
                            button.style.marginLeft = '10px';
                            button.style.borderRadius = '5px';
                            button.classList.add('float-end');
                            button.addEventListener('click', function() {
                                setEvent(info.event);
                                presentInfoModal();
                            }
                            );

                            // add button to the extreme right
                            info.el.querySelector('.fc-list-event-title').appendChild(button);
                        }

                    }
                }
            />
            <InfoMeetingModal />
            <Modal show={showModal}>
                <Modal.Header closeButton onClick={closeModal}>
                <Modal.Title>Schedule Meeting</Modal.Title>
            </Modal.Header>
            <Modal.Body >
                <Form >
                    <Form.Group controlId="datePicker">
                    <Form.Label className='form-label'>Date</Form.Label>
                    <DatePicker
                        selected={selectedDate}
                        onChange={handleDateChange}
                        dateFormat="yyyy-MM-dd"
                        className='form-date-picker'
                    />
                    </Form.Group>
                    <Form.Group controlId="startTimePicker">
                    <Form.Label className='form-label'>Start Time</Form.Label>
                    <DatePicker
                        selected={selectedStartTime}
                        onChange={handleStartTimeChange}
                        showTimeSelect
                        showTimeSelectOnly
                        timeIntervals={15}
                        timeCaption="Start Time"
                        dateFormat="h:mm aa"
                        className='form-date-picker'
                    />
                    </Form.Group>
                    <Form.Group controlId="endTimePicker">
                    <Form.Label className='form-label'>End Time</Form.Label>
                    <DatePicker
                        selected={selectedEndTime}
                        onChange={handleEndTimeChange}
                        showTimeSelect
                        showTimeSelectOnly
                        timeIntervals={15}
                        timeCaption="End Time"
                        dateFormat="h:mm aa"
                        className='form-date-picker'
                    />
                    </Form.Group>
                    <Form.Group controlId="meetingDescription">
                    <Form.Label>Meeting Description</Form.Label>
                    <Form.Control
                        type="text"
                        placeholder="Enter meeting description"
                        value={meetingDescription}
                        onChange={handleDescriptionChange}
                        className='form-text-box'
                    />
                    </Form.Group>
                </Form>
            </Modal.Body>
            <Modal.Footer>
              
                <Button variant="danger" onClick={closeModal}>
                Close
                </Button>
                <Button variant="dark" onClick={createMeeting}>
                Save
                </Button>
                <Spinner id='spinner' animation="border" role="status" hidden={!loading}> </Spinner>
            </Modal.Footer>
            </Modal>
        </div>
    );

    function InfoMeetingModal() {
        return (
            <Modal show={showInfoModal}>
                <Modal.Header closeButton onClick={closeInfoModal}>
                    <Modal.Title>Meeting Details</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    {
                        console.log(selectedEvent)
                    }
                        <div>
                        <p>Meeting ID: {selectedEvent.extendedProps.meetingId}</p>
                        <p>Meeting Password: {selectedEvent.extendedProps.meetingPassword}</p>
                        <p>Start Time: {
                            // format time to current zone in hh:mm am/pm format
                            new Date(selectedEvent.start).toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
                        } {currentZone}
                        </p>
                        <p>End Time: {
                            // format time to current zone in hh:mm am/pm format
                            new Date(selectedEvent.end).toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
                        } {currentZone}</p>
                        <p>Meeting Description: {selectedEvent.title}</p>
                        <div>Join Url: {selectedEvent.extendedProps.joinUrl}</div>
                    </div>
                    
                    
                </Modal.Body>
            </Modal>
        );
    }

The problem is when I am entering dates or times in the modals below, (by setting state) the events are refetched.

The events function just fetches the data source from my backend server. I saw a post that used useMemo to solve this issue. However I am quite new to react and web dev, I was not able to understand it (Fullcalendar re-fetch events after change in React state)

How can I fix this?

Explanation for error handling in nextJS getServerSideProps

This is an example how I’m using getServerSideProps to stream some video data.
Now I want to implement some error handling and I think I’m messing up a few things.

So there are a few possible errors I want to catch (and handle correctly):

  1. Wrong request method
  2. Missing parameter (hash)
  3. DB connection failed
  4. openDownloadStream error

For my understanding the try/catch should collect all errors which are occuring in the try part.
But how do I handle those errors? Should I…

  • throw the error
  • call console.error()
  • use res()

to get the best display of the error message. Mongodb will give me some other error structure then any other function which is failing.

export const getServerSideProps: GetServerSideProps = async ({
  res,
  req: { method },
  query: { hash }
}) => {
  if (method !== 'GET') {
    res.statusCode = 405
    res.end() // Is this correct?
    return
  }
  if (!hash) return { notFound: true }

  try {
    const database = await mongodb() // catch connection error
    const bucket = new GridFSBucket(database)

    res.writeHead(200, { 'Content-Type': 'video/mp4' })
    bucket
      .openDownloadStream(hash)
      .on('data', (chunk) => {
        res.write(chunk)
      })
      .on('end', () => {
        res.end()
      }) 
      .on('error', (err) => {
        // catch this error
      })     
  } catch (error) {
    // how to handle `error` correctly?
    res.statusCode = 500
    res.json({ error });
    if (error instanceof MongoServerError) {
      console.error(error)
    }
    throw error
  }
}

How to get latitude and longitude from video file in ReactJs

I need to extract GPS information from a video file, but I couldn’t find any library that supports it. For images, I use the EXIF-JS library, but it doesn’t support the MP4 and MOV formats.

Here is my video upload function, and I’m using ReactJS:

onUploadVideo = async (e) => {
    let file = e.target.files[0];
    window.URL = window.URL || window.webkitURL;
    const video = document.createElement('video');
    video.preload = 'metadata';
    const videoDuration = await new Promise(resolve => {
      video.onloadedmetadata = function () {
        window.URL.revokeObjectURL(video.src);
        resolve(video.duration);
      }
      video.src = URL.createObjectURL(file);
    });
    if (videoDuration >= ALLOW_VIDEO_DURATION) {
      this.props.actions.showToast(true, { toastType: ERROR, toastInfo: MESSAGE_ERROR_OVER_ALLOW_VIDEO_DURATION_UPLOAD.replace("%s", file.name) });
      return;
    }

    this.isUploadImg = true;
    this.setState({
      isUploadding: true
    })
    let data = new FormData();
    data.append('photo', file);

    this.props.actions.userFilePostActions(Actions.ActionTypes.UPLOAD_ADVENTURE_VIDEO(this.generateFileName('mp4')), data, getAccessToken(this.props.state.login_data));
  }

setting up gtag with inertia / vue

Does anyone have any experience setting up gtag in inertia / vue.

so in non spa application you can just set it up like this

<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxx"></script>  
<script>  
  window.dataLayer = window.dataLayer || [];  
    function gtag(){dataLayer.push(arguments);}  
      
    gtag('js', new Date());  
    gtag('config', 'G-xxxxxxx');  
</script>

but i’m presuming i’ll need to so something like this

<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxx"></script>  
<script>  
  window.dataLayer = window.dataLayer || [];  
    function gtag(){dataLayer.push(arguments);}    
</script>
// not sure where to put this app.js?

router.on('navigate', (event) => {  
      gtag('js', new Date());  
      gtag('config', 'G-xxxxxxx');
})

would the router events have access to window on the inital ssr page load?

any help appreciated

Mapbox/Maplibre and WMS layer

I know that question asked many times but I didn’t find solution.

I work with MapboxGL/MaplibreGL and when I add WMS layer, the console returns all time

Access to fetch at 'https://wms.myurl.fr/qgis?map=projects/test_wms1.qgs&bbox=136975.15468703583,5371382.851655904,146759.09430753812,5381166.7912764065&format=image/png&service=WMS&version=1.3.0&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=carte_moissac' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

For information, this problem come from MaplibreGL (and lonely) because my WMS layer works with LeafletJS.

Headers are present ahead to my php file like that :

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Credentials: true");
?>

How do you go about it?

Thanks

Sylvain

I am looking for to add WMS layers into my app carto.

I am looking for add wms layer into my Mapbox Application

detecting height with flex column and overflow child content

I’m wondering how I can make a child element (when the flex direction is set to ‘column’) occupy all the remaining space within its container. I want it to expand to the available space and trigger a scrollbar when its content exceeds that space.

I initially thought that using ‘flex-grow: 1;’ would do the trick, making the child element take up all the available space and adjusting its height accordingly. However, this doesn’t seem to work as expected. When the child has overflowing content, its height also overflows.

To address this issue, I stumbled upon a solution:

height: calc(100% – 40px);

While this works, it’s not ideal when dealing with multiple child elements, as calculating this for each one becomes cumbersome.

I’m seeking advice on a more efficient way to achieve this. Thank you for any insights you can provide!

How i can resolve this? Ty for answers

.container {
display: flex;
flex-direction: column;
height: 300px;
max-height: 300px; /* Set a fixed height for the container */
}

.child {
  border: 1px solid #ccc;
  padding: 10px;
}

.flex-grow {
    // height: calc(100% - 40px); // this is possible answer but what if i have multiply children?
  flex-grow: 1;
  align-self: stretch;
}

.scrollable {
  overflow-y: scroll; /* Enable vertical scrolling */
  height: 100%; /* Take up 100% of the available height */
}
<div class="container">
  <div class="child">Child 1</div>
  <div class="child flex-grow">
    <div class="scrollable">
      <div class="child">Child 2</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
      <div class="child">Child 1</div>
    </div>
  </div>
</div>

I am entering the valid phone number and when tries to backspace it’s not removing the space between brace and number. I have to hold the backspace

I am entering the valid phone number in lwc input field and when tries to backspace, it’s not removing the space between brace and number. I have to hold the backspace button to remove the backspace.

Format of phone number:
(123) 131-5135

enter image description here

handleInputPhone(event) {

    this.showError = false;

    this.errorPhone = '';

    const enteredValue = event.target.value;

    const digitsOnly = enteredValue.replace(/[^d]/g, ''); // Remove non-digits

    //console.log('TEST'+ digitsOnly);

    if (event.keyCode === 8) { // Backspace key

        digitsOnly = digitsOnly.slice(0, -1); // Remove the last digit

    } else if (event.keyCode === 46) { // Delete key

        digitsOnly = digitsOnly.slice(1); // Remove the first digit

    }



    if (digitsOnly === '') {

        this.conPhoneNumber = ''; // Reset to empty string or default value

    } else {

        let formattedValue = '(___) ___-____';

        let digitIndex =0;



        for (let i = 0; i < formattedValue.length; i++) {

            if (formattedValue[i] === '_') {

                if (digitIndex < digitsOnly.length) {

                    formattedValue = formattedValue.substring(0, i) + digitsOnly[digitIndex] + formattedValue.substring(i + 1);

                    digitIndex++;

                } else {

                formattedValue = formattedValue.substring(0, i);

                    break; // Stop replacing digits once we run out of entered digits

                }

            }

        }

Separate Database for each user login in Nodejs sequellize

I am developing an application where I need a separate database for each user.

So I need to change the database connection on every HTTP Request and use the database of the login user.

I’m Using Nodejs Sequelize for application development.

User Database

id username password database
1 user1 **** UserDb1
2 user2 **** UserDb2
3 user3 **** UserDb3
4 user4 **** UserDb4
. **** ……
n usern **** UserDbn

Let’s say User1 is making an API request so for that request the database should be UserDb1

How Can I implement the required feature?

Unhandled Runtime Error TypeError: destroy is not a function

I’m using nextjs trying make a component and getting Unhandled Runtime Error
TypeError: destroy is not a function with useEffect

"use client"
import { useEffect} from "react";

export default function Page() {
    // const [items, setItems] = useState([]);

    useEffect(async () => {
        console.log("hello world");
    }, []);
    

    return (<>
        <div style={{textAlign: "center"}}>Welcome to Items</div>
    </>);
}

getting Unhandled Runtime Error
TypeError: destroy is not a function
If i don’t pass async callback to the useEffect error will gone.

How to get the Xpath from the script tag

Eg- window.run.params={ Data: { —————–} }

The challenge is to get the Xpath from the script tag which holds all the hidden data in the webpage.

I have tried to inspect the webpage and get the Xpath for the script tag. But the Xpath is not working, its saying as invalid XPath.

Problem of JavaScript(Logic Building Question) [closed]

you are required to choose a place by yourself and given answer to every possible solution.for example: if we talk about a workspace we there many possible things available in the office. i.e. chairs, tables, fans and Ac.
considering following constraints:
workspace area: 67 meter in length 54 meter in width
table width is 3×4

  1. distance between tables should be 1/2 meter with maximum 3 number of lines
  2. distance between fans should be 1 meter with maximum 2 number of lines.
  3. gap between table lines should be 1 meter
  4. there can be 1 ac in 10*10 area.Solution should be dynamic with following constraints. if i provide area tell me total number of fans and tables and vice versa

How to make the function of this scenario