Mongo db isn’t updating my profile, I have tried markModified

Hello I have this problem where my profile isn’t updating so when I use the function in discord it just spams I’ve tried marking tasks as modified but that isn’t working either, any other things I could try? It finds the profile just well and does the changes when I log it but when its time to update it just forgets everything and doesn’t update

    async function reward(userID, task, interaction) {
  try {
    let profile = await profileModel.findOne({ user: userID });

    let profileTaskIndex = profile.tasks.findIndex((v) => v.name === task.name);
    if (profileTaskIndex === -1) return;

    profile.tasks.splice(profileTaskIndex, 1);

    if (task.rewardType === "item") {
      let found = items.find((v) => v.name === task.reward);
      if (!found) return;
      profile = await giveItem(userID, task.reward, profile);
    } else if (task.rewardType === "coins") profile.coins += task.reward;

    profile.markModified("tasks");
    await profile.save();
  } catch (error) {
    console.log(error);
  }
}

RESTfulAPIs problem with injectDB(conn) not initialized when runing get or post request

import mongodb from "mongodb"
const ObjectId = mongodb.ObjectId;

let reviews;

export default class ReviewsDAO {

   static async injectDB(conn) {
     if (reviews) {
       console.log("DB already injected");
       return;
     }

     try {
       console.log("Injecting DB...");
       const db = conn.db("Movies");
       reviews = await db.collection("reviews");

       if (reviews) {
         console.log("DB injection successful!");
         // Insert a test document to ensure the collection is created
         await reviews.insertOne({ test: "initial document" });
         console.log("Inserted test document to ensure collection creation.");
       } else {
         console.log("DB injection failed - reviews collection not found.");
       }
     } catch (e) {
       console.error(`Unable to set collection handles on ReviewsDAO: ${e}`);
       throw new Error("Database initialization failed.");
     }
   }




 static async addReview(movieid, user, review){
   try{
      if (!reviews) {
        throw new Error("Database not initialized - call injectDB first.");
      }
      
      console.log(movieid, user, review);
      
      let reviewDoc = {
             movieid: movieid,
             user: user,
             review: review,
      };
      console.log("inserting review into DB...");
      return await reviews.insertOne(reviewDoc);
   } catch(e){
       console.error(`Unable to Post review into db: ${e}`);
       return { error: e.message};
   }
 }


 static async getReview(reviewid){
    try{
      console.log("getting review from DB...");
      return await reviews.findOne({_id: ObjectId(reviewid)});
    } catch(e){
       console.error(`Unable to get review from db: ${e}`);
       return { error: e.message};
     }
  }



  static async updateReview(reviewid, user, review){
   try{
       console.log("updating review in DB...");
       return await reviews.updateOne({_id: ObjectId(reviewid)},{ $set: {user: user, review: review}});
   } catch(e){
      console.error(`Unable to update review in db: ${e}`);
      return { error: e.message};
   }
  }



  static async deleteReview(reviewid){
     try{
         console.log("deleting review from DB...");
         return await reviews.deleteOne({_id: ObjectId(reviewid)});
     }
     catch(e){
       console.error(`Unable to delete review from db: ${e}`);
       return {error: e.message};
     }
  }

   // assuming the movieid is a valid string
   static async getReviewsByMovieId(movieid){
      try{
         console.log("getting reviews from DB...");
         let cursor = await reviews.find({movieid: parseInt(movieid)});
         return await cursor.toArray();
      } catch(e) {
         return { error: e};
      }
   }



}

i run ~/SurprisedStrongPasswords$ curl -X POST https://440f059d-982e-4ad2-8414-cc9eac732569-00-89rw5y4qzvzj.spock.replit.dev/api/v1/reviews/new -H “Content-Type: application/json” -d ‘{“movieid”: 12, “user”: “beau”, “review”: “good”}’

and got {“error”:”Database not initialized – call injectDB first.”}~/SurprisedStrongPasswords$
i think the issue is with the injectDb function

Using UUID As Dynamic Namespace In Socket IO

Am developing a multi-tenant chat app and want each tenant to connect to their own namespace in socket io. Am using the id of the tenant which is UUID (ex: 5d056752-6643-4300-926f-5bcd5ed65722) as the namespace but am not able to connect to the server.

// Server

const namespace = this.io.of(/^[a-zA-Z0-9._-]+$/);
  namespace.on('connection', (socket: SocketWithUser) => {
}

The following regex don’t work as well:

- this.io.of(/^/w+$/);
- this.io.of(/^[w.-]+$/);
- this.io.of(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/);

// Client

const socket = io('localhost:5002/5d056752-6643-4300-926f-5bcd5ed65722', {
            reconnection: true,
            autoConnect: false,});
socket.connect();

The problem lies in the regex because it works if i use non-uuid string (ex: verizon) as namespace from the client.

What am i doing wrong?

Any pointers will help.

Chrome extensions unable to read the methods of the ‘sessions’ API

I am trying to develop an extension that will take tabs from one session and open them in another session. To do this I am using chrome’s sessions API.

However, when I run any code such as: chrome.sessions.getDevices().then((devices) => {...}

I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'getDevices')

This has happened with every single method that I have tried from the sessions API, and I have the following permissions in my manifest file:

"permissions": [
      "sessions",
      "tabs",
      "gcm",
      "contentSettings",
      "history",
      "identity",
      "processes",
      "search",
      "system.memory"
    ],

What could be the issue here?

Fullcalendar is not showing the timetable

am trying to include a fullcalendar, to a timetable i developed in the backend with laravel, the data are being fetched but it does not render the timetable content.

i have tried including console debug and try catch to see i can pickup why the content is not rendering on the calendar, here is copy of my code,

@extends('admin.layouts.admin')

@section('title', 'Time Table Calendar')

@section('admin')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.11.5/main.min.css" />

<div class="container">
    <div class="card p-3">
        <h1>Time Table Calendar</h1>
        <div id='calendar'></div>
    </div>
</div>
@endsection

@section('javascript')
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.11.5/main.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    try {
        var calendarEl = document.getElementById('calendar');

        // Parse the PHP-encoded JSON data
        var timetables = @json($timetables);
        console.log('Timetables:', timetables);

        // Process timetables into FullCalendar events
        var events = timetables.map(function(timetable) {
            try {
                // Parse start and end times
                var startDateTime = new Date(timetable.start_time);
                var endDateTime = new Date(timetable.end_time);

                // Extract only the time part
                var startTime = startDateTime.toTimeString().slice(0, 5);
                var endTime = endDateTime.toTimeString().slice(0, 5);

                // If end time is earlier than start time, assume it's the next day
                if (endDateTime < startDateTime) {
                    endDateTime.setDate(endDateTime.getDate() + 1);
                }

                // Calculate duration in minutes
                var durationMinutes = (endDateTime - startDateTime) / (1000 * 60);

                return {
                    title: timetable.course.code + ' - ' + timetable.teacher.user.first_name + ' ' +
                        timetable.teacher.user.last_name,
                    startTime: startTime,
                    endTime: endTime,
                    daysOfWeek: [timetable.day_of_week %
                        7
                    ], // Ensure it's 0-6 (0 = Sunday, 6 = Saturday)
                    startRecur: timetable.semester.start_date,
                    endRecur: timetable.semester.end_date,
                    duration: {
                        minutes: durationMinutes
                    },
                    extendedProps: {
                        department: timetable.department.name,
                        room: timetable.room,
                        course_name: timetable.course.title,
                        teacher_name: timetable.teacher.user.first_name + ' ' + timetable.teacher
                            .user.last_name
                    },
                    backgroundColor: getColorForDepartment(timetable.department_id),
                    borderColor: getColorForDepartment(timetable.department_id)
                };
            } catch (eventError) {
                console.error('Error processing timetable entry:', eventError, timetable);
                return null; // Return null for failed entries
            }
        }).filter(event => event !== null); // Remove any null entries

        console.log('Processed events:', events);

        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'timeGridWeek',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            events: events,
            slotMinTime: '06:00:00',
            slotMaxTime: '24:00:00',
            eventClick: function(info) {
                alert('Course: ' + info.event.extendedProps.course_name + 'n' +
                    'Teacher: ' + info.event.extendedProps.teacher_name + 'n' +
                    'Department: ' + info.event.extendedProps.department + 'n' +
                    'Room: ' + info.event.extendedProps.room);
            }
        });

        calendar.render();
    } catch (error) {
        console.error('Error setting up calendar:', error);
        // Optionally, display an error message to the user
        if (calendarEl) {
            calendarEl.innerHTML =
                '<p>An error occurred while loading the calendar. Please try refreshing the page.</p>';
        }
    }
});

function getColorForDepartment(departmentId) {
    try {
        const colors = [
            '#FF5733', '#33FF57', '#3357FF', '#FF33F5', '#33FFF5', '#F5FF33',
            '#FF3333', '#33FF33', '#3333FF', '#FF33F5', '#33FFFF', '#FF33FF'
        ];
        return colors[departmentId % colors.length];
    } catch (error) {
        console.error('Error in getColorForDepartment:', error);
        return '#CCCCCC'; // Default color in case of error
    }
}
</script>
@endsection


<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class TimeTable extends Model
{
use HasFactory;
const STATUS_DRAFT = 'draft';
const STATUS_PENDING_APPROVAL = 'pending_approval';
const STATUS_APPROVED = 'approved';
const STATUS_ARCHIVED = 'archived';


protected $fillable = [
    'academic_session_id',
    'semester_id',
    'department_id',
    'level',
    'day_of_week',
    'start_time',
    'end_time',
    'course_id',
    'teacher_id',
    'room',

    'status',
    'created_by',
    'updated_by',
    'class_duration',
    'is_current',
    'class_date'
];
protected $casts = [
    // 'start_time' => 'time',
    // 'end_time' => 'time',
    'day_of_week' => 'integer',
    'level' => 'integer',
    'class_duration' => 'integer',
    'is_current' => 'boolean',
    'start_time' => 'datetime',
    'end_time' => 'datetime',
    'class_date' => 'date',
];

public function creator()
{
    return $this->belongsTo(User::class, 'created_by');
}

public function updater()
{
    return $this->belongsTo(User::class, 'updated_by');
}



public function getClassDateAttribute()
{
    return $this->attributes['class_date'] ? CarbonCarbon::parse($this->attributes['class_date'])->format('jS F Y') : null;
}


public function getDurationAttribute()
{
    return $this->start_time->diffInMinutes($this->end_time);
}

public function getWeeklyHoursAttribute()
{
    return $this->duration / 60;
}
public function academicSession()
{
    return $this->belongsTo(AcademicSession::class);
}

public function semester()
{
    return $this->belongsTo(Semester::class);
}

public function department()
{
    return $this->belongsTo(Department::class);
}

public function course()
{
    return $this->belongsTo(Course::class);
}

public function teacher()
{
    return $this->belongsTo(Teacher::class);
}

public function hasConflict(Timetable $other)
{
    return $this->day_of_week === $other->day_of_week &&
        $this->start_time < $other->end_time &&
        $this->end_time > $other->start_time &&
        (($this->room === $other->room) ||
            ($this->teacher_id === $other->teacher_id) ||
            ($this->course_id === $other->course_id &&
                $this->level === $other->level &&
                $this->department_id === $other->department_id));
}

public static function getDayName($day)
{
    $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    return $days[$day - 1] ?? '';
}

public function approver()
{
    return $this->belongsTo(User::class, 'approved_by');
}

public function isEditable()
{
    return in_array($this->status, [self::STATUS_DRAFT, self::STATUS_PENDING_APPROVAL]);
}
}

public function calendarView()
{
$timetables = TimeTable::with(['course', 'teacher.user', 'department', 'academicSession', 'semester'])
// ->where('status', TimeTable::STATUS_APPROVED)
->get();



return view('admin.timeTable.calender', compact('timetables'));
}

Ruby on rails – I want a behavior, when validity is true, but validity is always true, as Required: false,

My issue is precisely this. I am using simple forms and one of my sections (one_liner), is not behaving as wanted. As it can be seen from the picture, the label should not hover, if nothing is inputted into the form, I achieve this in “full name” and “company name” by setting Required: True, because they ARE required to submit the form. However, the one_liner is not required and must not be required and as such it will always be valid. I added a minlength to try and invalidate it, when an input less than 1 character is inputted, but that only works when its in focus.
Image 1
Image 2

So my question is this: How do I make the label stay in place, and when something is written in the one_liner input field, the label floats?

I get the wanted behavior, visually, when I change the “&:valid ~ label” to “&invalid ~ label”. This only works because, now I just reversed the playing field… Since the one_liner input field is always valid, the label will stay in place but this means I must never be valid, but I cannot submit the form if the one_liner isn’t valid..

  &.required{
    &:focus ~ label,
    &:valid ~ label {
      color: map-get($foundation-palette, 'primary');
      top: 2px;
      left: 31px;
      font-size: 12px;
    }
  }
  &.optional {
    &:focus ~ label,
    &:valid ~ label{
      // Styles for when the input is focused
      color: map-get($foundation-palette, 'primary');
      top: 2px;
      left: 31px;
      font-size: 12px;
    }
    
            = f.fields_for :settings, current_user.settings || current_user.build_settings do |settings_form|
              = settings_form.input :one_liner,
                      as: :string,
                      required: false,
                      placeholder: false,
                      label: t('.oneliner_placeholder'),
                      wrapper: :input_field_wrapper,
                      input_html: { class: 'secondary_form-control', minlength: "1" }

This only works because, now I just reversed the playing field… Since the one_liner input field is always valid, the label will stay in place but this means I must never be valid, but I cannot submit the form if the one_liner isn’t valid..

How does the string become different encoding and then decoding, and how can I edit my code so it isn’t different?

I am working on a javascript code to heavily encode strings.

function splitIntoChunks(str, chunkSize) {
  let chunks = [];

  for (let i = 0; i < str.length; i += chunkSize) {
    let chunk = str.slice(i, i + chunkSize);
  }
  return chunks;
}

function baseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

function stringToNumber(string, bool) {
  var str = string;
  let num = BigInt(0);
  for (let i = 0; i < str.length; i++) {
    num = num * BigInt(1103871) + BigInt(str.charCodeAt(i));
  }
  if (bool) {
    console.log(string);
    console.log(numberToString(num, false));
  }
  return num;
}

function numberToString(number, bool) {
  let str = '';
  var num = number;
  while (num > 0) {
    let charCode = Number(num % BigInt(1103871));
    str = String.fromCharCode(charCode) + str;
    num = num / BigInt(1103871);
  }
  if (bool) {
    console.log(number);
    console.log(stringToNumber(str, false));
  }
  return str;
}

function encode(string) {
  var encodedString = encodeURIComponent(string);
  var array = encodedString.split("");
  var newNumberArray = [];
  array.forEach(char => {
    newNumberArray.push(JSON.stringify(10 + char.charCodeAt(0)));
  })
  return encodeURIComponent(numberToString(BigInt(parseInt(newNumberArray.join(""))), true));
}

function decode(string) {
  var weirdUnicodeCharacters = decodeURIComponent(string);
  var jumbledArray = splitIntoChunks(stringToNumber(weirdUnicodeCharacters, true).toString(), 2);
  var resultString = "";
  jumbledArray.forEach(num => {
    resultString = resultString + String.fromCharCode(parseInt(num) - 10);
  })
  return resultString;
}

/* Usage:
encode(str);
decode(str);
*/

// Testing: 
console.log(encode("Hello world!"));
console.log(decode(encode("Hello world!")));

For some reason, the string is being distorted, maybe due to a round-off error or a bug in javascript. I have looked through my code, and I can’t seem to find an error. I even added some debugging using console.log. It may be due to the fact I am using BigInt and normal numbers. I am new to javascript and StackOverflow, so some of my code isn’t that efficient. Thanks so much!

Best tools to develop AR web apps with QR reading feature

I am in search of tools that can help me develop AR web apps with (if possible) the possibility to read QR codes. I am already familiar with Three.js, and I am aware that you can do this on Unity but for some reason I really struggle to learn it by myself or with tutorials, but if it’s the best tool I will for sure try to learn it in some other way. Point is I would really like to know what the best tool is to do this (program, JS library, …) so give me ANY suggestion you want. Thanks in advance.

Wrapping a number within a specific range

I have come across the below wrapping formula to wrap a number x within a range [min, max].

const wrappedValue = (x - min) % (max - min + 1) + min;

I am trying to understand the formula.

Specifically, I am not able to understand why we need to subtract min from x?

Why the below formula cannot be used?
x % (max - min + 1) + min

The scrollbar only works when viewed through devtools

I have a website where I’m trying to make a scroll bar. I want to make it so that cards can be scrolled horizontally thanks to the cursor and it works! In the html there is a section with class “card”, in it a div with class “card-content” It works when viewed through developer tools, but it doesn’t work when the file is just opened locally! What could be the problem? Checked it in other browsers too – I don’t understand what it is

I feel like the answer is simple, but I don’t see it :/

const cardContainer = document.querySelector('.card');
let isDown = false;
let startX;
let scrollLeft;

cardContainer.addEventListener('mousedown', (e) => {
  isDown = true;
  cardContainer.classList.add('active');
  startX = e.pageX - cardContainer.offsetLeft;
  scrollLeft = cardContainer.scrollLeft;
  cardContainer.style.cursor = 'grabbing';
});

cardContainer.addEventListener('mouseleave', () => {
  isDown = false;
  cardContainer.style.cursor = 'grab';
});

cardContainer.addEventListener('mouseup', () => {
  isDown = false;
  cardContainer.style.cursor = 'grab';
});

cardContainer.addEventListener('mousemove', (e) => {
  if (!isDown) return;
  e.preventDefault();
  const x = e.pageX - cardContainer.offsetLeft;
  const walk = (x - startX) * 2;
  cardContainer.scrollLeft = scrollLeft - walk;
});
.card {
  display: flex;
  flex-direction: row;
  background-color: #fff;
  width: 100%;
  min-height: 200px;
  overflow-x: scroll;
  scroll-behavior: smooth;
  cursor: grab;
}

.card--content {
  background-color: #e74c3c;
  min-width: 200px;
  min-height: 200px;
  margin: 5px;
  flex-shrink: 0;
}

how to fire only last event listener

I am faced with a problem related to a number of identical event listeners. The main problem is that these events are executed in the order they were added: first in, first out. How can I change this order so that events are executed in reverse order: first in, last out? I know about capture property and it helps but not quite good.

Let’s say first of all i open message top bar:

const MessageTopBar = ({
    onClose,
    title,
    mainIconSlot,
    closeIconSlot,
    description,
    preventClose
}: MessageTopBarProps) => {
    
    React.useEffect(() => {
        const handleClose = (event: KeyboardEvent) => {
            event.stopImmediatePropagation();

            !preventClose && event.key === 'Escape' && onClose();
        }

        document.addEventListener('keydown', handleClose);

        return () => {
            document.removeEventListener('keydown', handleClose)
        };
    }, [])

    return (
        // jsx
    );
};

It’s our first listener. Now i open details component:

const OutletDetails = ({
    onClose,
    name,
    description,
    type,
    info,
    shouldCloseOnClickOutside = true
}: {
    description?: string;
    info?: React.ReactNode;
    name: string;
    type: FeedTypes;
    onClose: () => void;
    shouldCloseOnClickOutside?: boolean;
}) => {

    React.useEffect(() => {
        if (!containerRef.current) return;

        const handleClick = ({ target }: MouseEvent) => {
            target instanceof Node && !containerRef.current?.contains(target) && onClose();
        };

        const handleKeyDown = (event: KeyboardEvent) => {
            event.stopImmediatePropagation();

            event.key === 'Escape' && onClose();
        };

        document.addEventListener('keydown', handleKeyDown);
        shouldCloseOnClickOutside && document.addEventListener('click', handleClick);

        return () => {
            document.removeEventListener('click', handleClick);
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    return (
       // jsx
    );
};

It’s our second listener. Now open modal:

export const ModalProvider = ({ children }: { children: React.ReactNode }) => {
    // another code here

    const handleEscapeDown = (event: KeyboardEvent) => {
        !isAsyncActionLoading && event.key === 'Escape' && closeModal();
    };


    const handleKeyDown = (event: KeyboardEvent) => {
        event.stopImmediatePropagation();
        
        const keyListeners = {
            Tab: handleTabDown,
            Escape: handleEscapeDown,
        };

        keyListeners[event.key as keyof typeof keyListeners]?.(event);
    };

    React.useEffect(() => {
        if (!modals.length || !bodyRef.current) return;

        bodyRef.current.focus();

        document.body.style.paddingRight = window.innerWidth - document.body.offsetWidth + 'px';
        document.body.classList.add('overflow-hidden');

        document.addEventListener('keydown', handleKeyDown, true);

        return () => {
            document.body.classList.remove('overflow-hidden');
            document.body.style.paddingRight = '0';
        
            document.removeEventListener('keydown', handleKeyDown, true);
        };
    }, [isAsyncActionLoading, modals, handleKeyDown]);

    return (
       // jsx
    );
};

This is our third event listener. Because we used useCapture as true, the modal will close first, the message top bar second just because this event was added earlier than the details. How can I change this order? If I use useCapture as true for every listener, it will close the message top bar first, even if the modal open.

Facing setupProxy issue in my react application

I’m facing an issue in my react application where I have created setupProxy.js file in that I have added multiple environment url (.development, .test) . Development port is running “http://localhost:8080 & test is running “/bizcomp.test.com”. When I run my app using test env (non-prod) its working properly but if I run my app using backend port (8080) path is not accepting. Please find below setupProxy.js & error screenshot.
Below is the api call which we use in frontend
http://localhost:8080/bizcomp/restservices/v1/service/seller/comptitle.

Note: Issue which I’m checking “/bizcomp” path in setupProxy is working. But I run my app using test env “/bizcomp” is working properly.

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  let targetUrl; 

  // Set the target URL based on the current environment

  if (process.env.NODE_ENV === 'development') {
    targetUrl = "http://localhost:8080"
  } else if (process.env.NODE_ENV === 'test') {
    targetUrl = process.env.REACT_APP_OIDC_REDIRECT_URI;
  } else {
    console.error('Unknown environment:', process.env.NODE_ENV);
    return;
  } 
  console.log(`Proxying requests to: ${targetUrl}`);

  // Proxy API requests to the backend server
  app.use(
    '/bizcomp',
    createProxyMiddleware({
      target: targetUrl,
      changeOrigin: true,
      secure: false, // Disable SSL verification if necessary
      onProxyReq: (proxyReq, req, res) => {
        console.log(`Proxying request: ${req.method} ${req.url}`);
      },
      onError: (err, req, res) => {
        console.error('Proxy error:', err);
        res.status(500).send('Proxy error');
      },
    })
  );
};

enter image description here

Display Object values from an API object

I’m trying to create a Currency Conversion using an API, but I’m struggling finding out how to match the currency with it’s value.

<div class="container">
    <div class="form">
        <div class="grid-container">
            <div class="currency-from">
                <input type="number" id="main-currency">
                <select onchange="changeCurrency()" id="mainCurrency">
                </select>
            </div>
            <div class="currency-to">
                <input type="number">
                <select id="otherCurrency">
                    <option value="EUR">EUR</option>
                </select>
            </div>
        </div>
        <br>
        <input type="number" name="" id="" disabled>
</div>
const mainCurrency = document.getElementById('mainCurrency');
const inputCurrency = document.getElementById('main-currency');

function changeCurrency() {

    fetch(`https://open.er-api.com/v6/latest/USD`)
    .then(response => {
        return response.json();
    })
    .then(currency => {


        for (const [key, value] of Object.entries(currency.rates)) {
            const currencyName = document.createElement('option');
            currencyName.innerHTML = key;
            currencyName.text = key;
            mainCurrency.appendChild(currencyName);
            inputCurrency.value = value;
          }
    })
}

changeCurrency()

It’s always giving me the last value of the object.

nextJS server actions fails with react query on special syntax

I have small in file my nextJS project that has the "use server" annotation. It exports a function:

export async function getData() {
  Promise.resolve({foo: "bar"});
}

And i use React Query in a client component:

const { data, isLoading, error } = useQuery({
  queryKey: ['solves'],
  queryFn: getData,
});

This does not work and throws the error:

Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.

I can resolve this issue by changing the syntax to

const { data, isLoading, error } = useQuery({
  queryKey: ['solves'],
  queryFn: () => getData(),
});

Why is that? What is the difference between queryFn: getData and queryFn: () => getData()? I thought the first one was just syntactic sugar.