where is problem in code axios.get “response.data”?

Set data

export const setIngredients = (ingredients) => {return { type: actionTypes.SET_INGREDIENTS,ingredients : ingredients}}

Get data

export const initIngredients = () => {return dispatch => {axios.get('....').then(response => {dispatch(setIngredients(response.data));}).catch( error => {dispatch(fetchIngredientsFailed())})} }

Error:

Objects are not valid as a React child (found: object with keys {objectId, name, createdAt, updatedAt, value}). If you meant to render a collection of children, use an array instead.

return dispatch => {
axios.get(‘……’).then(response => {dispatch(setIngredients(response.data));}).catch( error => {dispatch(fetchIngredientsFailed())}

Can upload image from ImagePicker.openPicker but not ImagePicker.openCamera, react native

I’m currently developing an app in react native.

In the app, a user has a profile image and can update it by
either choosing one from gallery or taking a new one with the camera.

The library used for this is ‘react-native-image-crop-picker’.

To choose an image ImagePicker.openPicker is used.
To take a new picture ImagePicker.openCamera is used.

After updating his/her profile image it is also updated to a aws server.

This is the code for that:

static uploadFile = async (filePath: string, idToken: string): Promise<AxiosResponse> => {
    return new Promise(async (resolve, reject) => {

      console.log("filepath: " + filePath);

      // when taking: filepath: /data/user/0/com.myapp/files/1685872451229.jpg
      // when picking: filepath: /data/user/0/com.myapp/files/1685872572898.jpg

      const formData = new FormData();
      formData.append('file', {
        name: 'profileImage',
        uri: 'file://' + filePath,
        type: 'image/jpg'
      });

      try {
        const response = await axios.post(`${API_BASE_URL}`, formData, {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'multipart/form-data',
            Authorization: idToken
          }
        });
        resolve(response);
      } catch (error) {
        console.error(error);
        reject(error);
      }
    })
  }

When a new profile image is chosen or taken I use react-native-fs ‘moveFile’
to update the image in local storage, after the previous has been deleted.

My problem is this:

Whenever I upload an image chosen from Gallery it works just fine, but when uploading a taken picture it times out after a few seconds with:

[AxiosError: Request failed with status code 504]

Are the images in a different format or what might cause this error for Axios?

WHAT I HAVE ALREADY TRIED:

I have tried to set the image quality to a lower percentage, hoping it would solve the problem if the taken picture was “too large”.

I have tried the option forceJpg: true for Imagepicker.openCamera.

JAVASCRIPT: Class method returns a promise. But I want it to return the resolved result. How do I rewrite the class method?

This is my class.

export MyClass {
    
    private readonly ServiceEndpoint: string = 
    "/xxx/xxx.DMS.UI.Root/Services/ConfigurationAPI.svc/";
    
    
    public async GetAllCompanies(): Promise<CompanyDto[]> {
    return fetchAsync(
        `${this.ServiceEndpoint}Company`,
        'GET'
        )
      .then(value => value.GetAllCompaniesResult);
  }

}

Presently, this method returns a Promise <CompanyDto[]>. How do I rewrite it so that it returns only the result CompanyDto[]?

typescript Narrowing and func Overloads not work

function funa (b:string):number
function funa (b:string[]):number[]
function funa (b:string|string[]):number|number[]{
  const flag = typeof b === 'string'
  // can't use if(flag)
  if(typeof b === 'string') {
    b = [b]
  }
  let arr = []
  for(let i of b){
    arr.push(parseFloat(i))
  }
  return flag? arr[0]:arr
}

function func (b:string|string[]):number|number[]{
  // can't direct return funa(b)
  if(typeof b ==='string')
    return funa(b)
  else
    return funa(b)
}

tsplayground

How should I modify this correct code

How to make emphasized zone in the element to be transparent in CSS

I have a slider that is built using <input type="range">. And I want to make an emphasized zone background content to be seen clear. Problem image.

I want to get something like that ( I mean when my thumb is over some part of track, then background in this part of track becomes trasparent and content is clearly seen) Expected result

.wrapper {
  height: 200px;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.slider-parent {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 200px;
}

.slider-parent input {
  position: absolute;
  z-index: 0;
  background-color: transparent;
}

.slider-parent input[type="range"]::-moz-range-track {
  width: 100%;
  height: 300px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 1px 1px 2px #a6a6a6;
  background-color: rgba(237, 231, 225, 0.75);
  border-radius: 4px;
  border: 2px solid #f27b7f;
}

.slider-parent input[type="range"]::-moz-range-thumb {
  box-shadow: 1px 1px 2px #a6a6a6;
  border: 2px solid #f27b7f;
  height: 300px;
  width: 25%;
  border-radius: 0px;
  background-color: rgba(237, 231, 225, 0.1);
  cursor: pointer;
}
<div className="wrapper">
  <Bar>...</Bar>

  <div className="slider-parent">
    <input type="range" min="1" max="600" />
  </div>
</div>

I was trying to find solution. But found only a few solutions with background-image and background-image: -webkit-radial-gradient(…) that isn’t a match for this case.

Any suggestions?

Node.js Express: Unexpected behavior when calling /newblogs endpoint

this is the code i was working on:

import express from 'express'
import * as blogControler from '../controler/blogControler.js'
import * as authControler from '../controler/authControler.js'

const blogRouter= express.Router()

blogRouter.use(authControler.isVerified)

blogRouter.route('/allblogs').get(blogControler.showallblogs)
blogRouter.route('/:id').get(blogControler.find_blog)
blogRouter.route('/newblogs').get(blogControler.newpost)


export default blogRouter;

when i tried to hit /newblogs endpoint it was throwing error.

I tried many things and finally when i changed the position of /newblogs endpoint it worked!!
the updated code is given below –

import express from 'express'
import * as blogControler from '../controler/blogControler.js'
import * as authControler from '../controler/authControler.js'

const blogRouter= express.Router()

blogRouter.use(authControler.isVerified)

blogRouter.route('/allblogs').get(blogControler.showallblogs)
blogRouter.route('/newblogs').get(blogControler.newpost)
blogRouter.route('/:id').get(blogControler.find_blog)

export default blogRouter;

It is confusing /:id and /newblogs i noticed that when i was calling /newblogs in the first code snipet it was calling function related to /:id .I think it is confusing the route between /:id and /newblogs.
but why is that happening?

Is there a way to give an if statement for a date to be disabled if start & end date are the same?

This is a calendar booking system, I have a bug that if i book for a single day it books for the following day also. The solution i believe is to have a statement where if both start/end date is the same, then book both slots.

However i am struggling to right this in the right format.

function wpkGetThisDateSlots( date ) {

    var slots = {
        isFirstSlotTaken: false,
        isSecondSlotTaken: false
    }
    

if ( typeof disabledDates !== 'undefined' ) {
            if ( wpkIsDateInArray( date, wpkStartDates )) {
                slots.isFirstSlotTaken = slots.isSecondSlotTaken = true;
                return slots;
            }
   if ( typeof disabledDates !== 'undefined' ) {
            if ( wpkIsDateInArray( date, wpkEnddate )) {
                slots.isFirstSlotTaken = slots.isSecondSlotTaken = true;
                return slots;
        }
        }

        }

I have tried formatting the start date and end date so that if the same date is selected. Disable the date. However I understand that logically wouldn’t work.

if (typeof Startdate == typeof Enddate )

or if (slots.Firstslottaken == slots.Secondslottaken) {

}

Easier way to use both external module’s CDN and packages in sveltekit?

In sveltekit I have my common js files that run on both client and server. This will reuse the same code on both the server and client side.

This uses the moment.js module.

(This is just an example where both CDN and npm exist. I actually use date-fns.)

Anyway, I want to run it as a CDN in the client environment and bundle and operate the node package on the server.

So my common js file originally looked like this:

import moment from 'moment';

export const mylib = () => {
  return moment().format();
};

The sveltekit page also uses moment.js:

<script>    
    import moment from 'moment';
</script>
<div>
    {moment().format()}
</div>

This works fine. Just, my bundle includes moment.js.

So I tried several things. And I succeeded in the following way. But it’s incredibly dirty.

First, I imported the CDN in app.html and created an onload event:

<script async defer src="https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js" onload="momentLoad()"></script>
<script>
    window.momentWaits = [];
    const momentLoad = () => {
        for(const momentWait of window.momentWaits){
            momentWait();
        }
        delete window.momentWaits;
    };
</script>

And change moment.js in package.json from devDependencies to runtime dependencies.

{
    "dependencies": {
        "moment": "^2.29.4"
    }
}

And set build.rollupOptions.external in vite.config.js.

export default defineConfig({
    build: {
        rollupOptions: {
            external: ['moment']
        }
    },
});

And my common js file became like this:

let moment = null;
if(typeof window == 'undefined') {
  (async () => import('moment').bind((res) => moment = res.default));
}else {
  // eslint-disable-next-line no-undef
  const w = window;

  if(w.moment){
    moment = w.moment;
  }else{
    w.momentWaits.push(() => {
      moment = w.moment;
    });
  }
}

export const mylib = () => {
  if(!moment){
    console.log('not yet.');
    return;
  }
  return moment().format();
};

As above, if typeof window == 'undefined' is used when checking the browser environment, an error occurs saying that await was used at the top level when building vite, so it was set as a function. Changing browser to $app/environment solved it:

import { browser } from '$app/environment';
let moment;
if(!browser) {
  moment = (await import('moment')).default;
}else {
  // ...
}

However, my js file can be executed in an environment other than svelte, so I do not do it.

Finally, the svelte page changes:

<script>
    import { onMount } from 'svelte';

    let moment = null;
    onMount(async () => {

        if(window.moment){
            moment = window.moment;
        }else{
            window.momentWaits.push(() => {
                moment = window.moment;
            });
        }

    });
</script>
<div>
    {#if moment}
        {moment().format()}
    {:else}
        wait...
    {/if}
</div>

As you can see, it’s very dirty. But it works. I’m sure there is a much easier way than this. I want to find it.

In particular, if there is an option to ignore some errors during the build process and keep building, it seems to save a lot of code.

Also, the reason why there is still no moment in the onMount event is the effect of the async defer attribute of the script tag. Is there a better event than onMount?

How can I change the value of :root in CSS with JavaScript to create a dark theme for my website? [duplicate]

I wanna make dark theme in my web site and I wanna to change value of :root in css when I press boutton i will use javascript for that but I dont know how can I change value of :root in css by js pls some one help me

:root {
    /* Colors */
    --main-white: rgb(237, 242, 244);
    --main-black: rgb(1, 22, 39);
    --light-blue: rgb(69, 123, 157);
    --dark-blue: rgb(29, 53, 87);



Replace keys in an object dynamically [closed]

I have an object as follows;

{
"myFldA-0": {id: 'A', disabled: true},
"myFldB-0": {id: 'B', disabled: true},
"myFldC-0": {id: 'C', disabled: true},
}

I want to replace the index 0 in this object with the dynamic value that I can pass in e.g. if I pass 3, the output should be:

{
"myFldA-3": {id: 'A', disabled: true},
"myFldB-3": {id: 'B', disabled: true},
"myFldC-3": {id: 'C', disabled: true},
}

Is it possible to achieve this using ES6?