Where to add/remove interceptors while different components are calling apis using an axiosinstance

I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)

Currently I have to do this for every single api call in each component. My current code is as follows

axios.js

import axios from 'axios';

 const baseURL = process.env.REACT_APP_BASE_URL;

 let headers = {};

//this never executes since we havent logged in yet
  
if(localStorage.token) {
  headers.Authorization = `Bearer ${localStorage.token}`; 
}

const axiosInstance = axios.create({

baseURL: baseURL,
headers,
});
  
export default axiosInstance;

Login.js (without interceptors)

  const printValues = e =>{
  e.preventDefault();
 axiosInstance.post('/auth', data)
 .then(res =>{
  console.log("writing token");
  dispatch(jwtTokenRecieved(res.data.token));
  
  const config = {
    headers:{
      Authorization:'Bearer '+res.data.token
    }
  }
  axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
    dispatch(isLoggedUser(res.data));
  })
  .catch(err =>{
    console.log(err);
  })

AddSampleTable.js

This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage

import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');

const retrieveSampleData = () =>{

const config = {
  headers:{
    Authorization:'Bearer '+ jwtToken,
    'Content-Type': 'application/json'
  }
}
axiosInstance.get('/batch/'+CoCData.id, config) 
    .then(function (response) {
      setSamples(response.data.samples);
    })
    .catch(function (error) {
      console.log(error);
    });
} 


}

Note I am using reducers and actions to set token into the localStorage as you see in

dispatch(jwtTokenRecieved(res.data.token));

i18Next: use locale only for some languages and use language + location for rest

I have a question for the i18next library. If I have these set of locales that are possible to be detected from the browser,

de
en-US
es
fr
it
ja
ko
pt-br
zh-cn
zh-tw

Is there a way to configure it where it respects the language only for some locales and not the other? for example, when it comes to en-US, I wish for the loaded language to be en so when I call the .language or .languages method, it will contain en instead of en-US. However, for the other locales that have a dash like pt-br, zh-cn, and zh-tw, they will remain untouched, (so NOT return just zh).

Is this possible?

thanks in advance!

Dragged HTML elements always follow the mouse loosely, is synchronous dragging with Javascript impossible?

Notice: This question is only about plain Javascript and HTML.

I’ve tried the usual method to move HTML elements around with the mouse inside a mousemove event function like so:

element.style.left = e.clientX - offset.x + 'px';
element.style.top  = e.clientY - offset.y + 'px';

Earlier I had captured the x-y offset inside an element.mousedown function and zeroed it in a document mouseup function.

The problem is that the HTML element always follows the mouse loosely, like it is attached via a rubber band. This happens because Javascript updates the HTML element’s position at least one or more frames later, which is annoying, and looks sloppy and poorly made.

To see this effect drag the object quickly horizontally from one edge of the screen to another on this codepen (that comes from another question). Then try moving a window on your PC to see the huge difference.

https://codepen.io/kosarh79/pen/wqXGdE

This is only one example, I’ve seen several, and all have the same problem. I’ve noticed that this issue is getting worse when there is a heavier element, like a form, since it takes more time to draw.

Creating functions in react with d3 to assign colors to value

I’m new to d3, and I had been reading their docs and look at examples but nothing comes close to what I need.
I’m using react and typescript.

I need to create 2 functions, one should look something like this:

mapColor(value, lowerBoundColor, upperBoundColor)
@param value {float} - A decimal float which is between 0 and 1.
@param lowerBoundColor {string} - A hex color code corresponding to a value of 0.
@param upperBoundColor {string} - A hex color code corresponding to a value of 1.
@returns {string} - A hex color code corresponding to the value parameter passed in.

And the secound like this:

linearMap(value, lowerBound, upperBound)
@param value {float} - A decimal float between lowerBound and upperBound.
@param lowerBound {float} - A decimal float which represents the minimum value of the dataset to be clamped.
@param upperBound {float} - A decimal float which represents the maximum value of the dataset to be clamped
@returns {float} - A decimal float between 0 and 1 which corresponds to the value parameter passed in.

This is what I have so far:

import React from 'react'
import * as d3 from 'd3'

var data = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,0.9,1]

const mapColor =  d3.scaleLinear()
.domain([0,1])
.range(["f4a261", "264653"])

How can I create those 2 functions in react to where they can be used as a component in the future.

Set select value with Javascipt [duplicate]

I Want to set the selected value of a html select with the help of javascript.
This is my current js code:

var g = document.getElementById('g');
g.value = '1';

While this is my select:

   <select id="g">
    <option value="" disabled selected>  Geschlecht...</option>
    <option value="1" id="M">Männlich</option>
    <option value="2" id="F">Weiblich</option>
  </select>

However this doesn’t seem to work as i get the following error:

Uncaught TypeError: Cannot set properties of null (setting ‘value’)

How can I create a custom button that attach with Video.JS in this React custom hook?

I have a React custom hook that takes in URL, options, autoplay props, everything is working fine.

But I created a totally fullscreen video with it (I want it to be like that). So that’s why I need to have a custom button.

Picture

At the very top of the left, you can see, I have already tried to create 2 buttons, but the problem is it bugged behind the Video.JS and won’t fade together with the Video.JS and will stay like that forever, which I don’t want, and I think I haven’t implemented it to Video.JS properly.

I just wrapped it inside the Video.JS custom hook. Is there anyways I can make it work?

Here’s what I’m trying to do in the custom Hook.

import React, { useEffect, useRef, useState } from "react"
import PropTypes from "prop-types"
import videojs from "video.js"
import "video.js/dist/video-js.min.css"
import "./videojs.css"
import videoJsContribQualityLevels from "videojs-contrib-quality-levels"
import videojsHlsQualitySelector from "videojs-hls-quality-selector"
videojs.registerPlugin("qualityLevel", videoJsContribQualityLevels)
videojs.registerPlugin("hlsQualitySelector", videojsHlsQualitySelector)

// eslint-disable-next-line import/prefer-default-export

const usePlayer = ({ src, controls, autoplay }) => {
    const options = {
        fill: true,
        fluid: true,
        preload: "auto",
        html5: {
            hls: {
                enableLowInitialPlaylist: true,
                smoothQualityChange: true,
                overrideNative: true,
            },
        },
        plugins: {
            qualityLevel: {},
            hlsQualitySelector: { displayCurrentQuality: true },
        },
    }
    const videoRef = useRef(null)
    const [player, setPlayer] = useState(null)

    useEffect(() => {
        const vjsPlayer = videojs(videoRef.current, {
            ...options,
            controls,
            autoplay,
            sources: [src],
        })
        setPlayer(vjsPlayer)

        return () => {
            if (player !== null) {
                player.dispose()
            }
        }
    }, [])
    useEffect(() => {
        if (player !== null) {
            player.src({ src })
        }
    }, [src])

    return videoRef
}

const VideoPlayer = ({ src, controls, autoplay }) => {
    const playerRef = usePlayer({ src, controls, autoplay })

    return (
        <>
            <div data-vjs-player>
            {/* I create a top-wrapper and put it inside here.
                But clearly it's not working as I intended */}
                <div className="top-wrapper">
                    <div className="top-left">
                        <button className="go-back-btn">Go back</button>
                    </div>
                    <div className="top-right">
                        <button className="go-next-btn">Go next</button>
                    </div>
                </div>
                <video ref={playerRef} className="video-js" />
            </div>
        </>
    )
}

VideoPlayer.propTypes = {
    src: PropTypes.string.isRequired,
    controls: PropTypes.bool,
    autoplay: PropTypes.bool,
}

VideoPlayer.defaultProps = {
    controls: true,
    autoplay: false,
}

export default VideoPlayer

Is there a JavaScript library to input better texts through forms and stuff? [closed]

I am currently working on a website that uses Node.js and Express for it’s back-end, besides other libraries. In the project, there is a lot of CRUDs i need to create, and two of them would be posts that include bold texts, images etc, similar to a blog post. I would like to know: is there a library or framework to input these more “complete” texts through HTML Forms and store them in a database? Like, i don’t want to just store plain text into the system, but it would be too complicated to program a way to input images, bold text, underlines etc and i don’t have much knowledge nor time to do that.

How to convert nested JSON into flat object?

What is the most efficient way of converting in JavaScript object like:

const entries = {
  "name": "Mustang",
  "parts": {
    "tire": "example",
    "wheel": "example" 
  }
}

into flat object like:

const converted = {
  "name": "Mustang",
  "parts/tire": "example",
  "parts/wheel": "example"
}

no matter how many nested object inside.

how to write a search Api with Pagination

I am new to nodejs. I am creating an api for searching a particular data from the inputs – date from, dateto and id to display some data in a table – o/p – (username, datetime, id) with pagination
JSON data

{
[
    {
        "userId":"1",
        "userName":"Jack",
        "dateTime":"2021-08-02 03:13:29",
    },
    {
        "userId":"3",
        "userName":"John",
        "dateTime":"2021-08-02 03:13:29",
    }
],
"totalRecords": 2,
"numberOfRecords": 2,
"page": 1
}

Here is my code

let data= {
logs:require('./logs.json'),
}
app.get('/logs', (req, res) => {
  if (req.headers.authorization) {
    res.status(200);
    res.send(JSON.stringify(logResponse(req.body));
  } else {
    res.status(401);
    res.send();
  }
});

const logResponse = (str) => {
  console.log(str)
  const logData = data.logs.filter((log) =>
    log.logName.toLowerCase().includes(str.toLowerCase())
  );
  const bodyData = { logs: logData };
  return { header: header(), body: bodyData };
};

Accessing React childs state

I have a React element that renders Child elements with a target state. this target state can change anytime and parent doesn’t have access at the moment.

const Parent = () => {
  function getTarget(){
    //TODO
  }

  return(
    <Button>get target</Button>
    {children.map(c=>{
      <Child props={props}/>
    })}
  )
}

const Child = (props) => {
  //props stuff
  const [target, setTarget] = useState(null)
  // this target would be changed by user as they interact.
  
  return(
    //child elements
  )
}

what I’m trying to do is to get the target state of the Child using button in the Parent with following restraints:

  1. There can be variable amount of Child elements, but only one of them are visible at a time.

  2. The “get target” button has to be in Parent, the “target” state has to be initialized in child, and it’s unknown.

because only on Child is active at a time, a solution that works for

return(
  <Button>get target</Button>
  <Child props={props}/>
)

is also fine.

JavaScript & Nodejs for PDF Editor and Saving Changes

I have developed a cloud application for my company and its in production now. My team now wants me to add one more feature to it. This feature will be a PDF editor. We do a lot of pdf editing on another software but if I can add that feature to the application I built, it will be a time saver. I have built couple cloud applications but not a PDF editor so I am not too sure how to go about this. I know on the frontend user will upload the pdf file and then call a post api to the server to interpret the pdf content and send it back to be displayed on the frontend? Am I thinking right? I am using nodejs for the backend. Node has pretty solid file apis.

How can render the same card with different values based on user input in a form?

I’ve been stuck on this problem for quite some time. I am using a couple of different states to render values inside a card after they have been input into the form. The first state takes in the values and changes the initial state. the second state takes in the values after a mathematical function has been performed and renders them onto the card. My desired outcome is a fully reset state that allows for new values to be entered, and then subsequently having a new card rendered beneath the initial card all whilst maintaining the previous values that have already been input.

    import Navbar from '../../components/NavBar'
import { FormControl, InputLabel, Input, Button, FormHelperText } from '@mui/material'
import ExpenseCard from '../../components/ExpenseCard'
import axios from 'axios'
import { React, useState } from 'react'
import ReactDOM from 'react-dom'
import { Grid } from '@mui/material'
import { categoryResult, calcSumTotal } from '../../utils/CategoryResult'

const Budget = () => {
  const [ categoriesToAdd, setCategoriesToAdd] = useState(0);
  const [ committedCategoriesToAdd, setCommittedCategoriesToAdd] = useState(0);
  const [ renderCardsAdded, setRenderCardsAdded] = useState({
    category: '',
    actualValue: 0,
    goalValue: 0,
    result: 0
  });
  
  // by building out the states in the budget page we have negated the need to use an expenseContext and import it, removing confusion. doing this also allows us to compile the functions that we need to use to handle changes in the form.
  const handleAddExpense =  (category, actualValue, goalValue) => {
    let result = categoryResult(actualValue, goalValue);
    setRenderCardsAdded({...renderCardsAdded, category: category, actualValue, goalValue, result });
  }

  const renderTheCard = () => {
    document.getElementById('renderhere').innerText = 
    <ExpenseCard category={renderCardsAdded.category} actualValue={renderCardsAdded.actualValue} goalValue={renderCardsAdded.goalValue} result={renderCardsAdded.result} />
  }
  const handleInputChange = ({ target: { name, value } }) => setExpenseState({ ...expenseState, [name]: value })

  const [ expenseState, setExpenseState ] = useState({ 
    category: ' ',
    goalValue: 0,
    actualValue: 0,
  })


 /// this is basically the expenseform from the components folder but i circumvented the necessity to import it by building it out on the budget page.
  const CategoryForm = () => [
  

    <FormControl>
      <Grid container rowSpacing={1} columnSpacing={{ xs: 1 }}>
        <Grid item xs={2}>
          <Input name="category" aria-describedby="expense category" value={expenseState.category} onChange={handleInputChange}/>
          <FormHelperText id="my-helper-text-1">expense category</FormHelperText>
        </Grid>
        <Grid item xs={2}>
          <Input type="number" name="actualValue" aria-describedby="actual value" value={expenseState.actualValue} onChange={handleInputChange}/>
          <FormHelperText id="my-helper-text-2">actual expense</FormHelperText>
        </Grid>
        <Grid item xs={2}>
          <Input type="number" name="goalValue" aria-describedby="goal value" value={expenseState.goalValue} onChange={handleInputChange}/>
          <FormHelperText id="my-helper-text-3">goal expense</FormHelperText>
        </Grid>
        <Grid item xs={2}>
          <Button onClick={
            () => {
            handleAddExpense(expenseState.category, expenseState.actualValue, expenseState.goalValue)
            renderTheCard()}}>Add</Button>
        </Grid>
      </Grid>
    </FormControl>
  ]
  return (
    <>
      <Navbar />
      <hr />
      <CategoryForm />
      <div id="renderedCategories">
      {[...Array(committedCategoriesToAdd)].map((value: undefined, index: number) => (
        <CategoryForm id={index + 1} key={index} />))}
        </div> */}
      <h1>This is the Budget Page</h1>
      <div id="renderhere"></div>
    </>

  )
}

export default Budget

this code currently renders Object Object to the page with no information displayed outside of that. Further, another issue I’ve encountered is the input form is only allowing me to input 1 character at a time and to further input characters i have to refocus the input. Not sure what is causing this… using MUI styling, and react.

How can I get the corresponding price from my feed based on my product name?

For my affiliate site I import a XML feed and then use the XML2JSON function to convert this to a JSON object. It looks like this:

{products: {…}}
products:
product: Array(6510)
[0 … 99]
0:
aw_deep_link: "https://www.awin1.com/pclick.php?p=21982055441&a=852189&m=12893"
aw_image_url: "https://images2.productserve.com/?w=200&h=200&bg=white&trim=5&t=letterbox&url=ssl%3Awww.spellenrijk.nl%2Fresize%2F18111_3wy7yf3_5638761353075.jpg%2F300%2F300%2FTrue%2Fblackfire-boardgame-sleeves-square-72x73mm.jpg&feedId=25919&k=1ab7328112246a7b95251ed47642ace5169a9583"
aw_product_id: "21982055441"
category_id: "0"
category_name: ""
currency: "EUR"
data_feed_id: "25919"
delivery_cost: "3,99"
description: "Bordspel sleeves met een afmeting van 72 x 73 mm. Deze verpakking bevat 100 sleeves. Geschikt voor: Catan card game, Anno 1701 card game, Summertime, Powergrid, Funkenschlag vele andere spellen. - Thickness 40 microns - Extra high clarity - Prevents bent corners - Prevents scratches - Perfect fitting for a lot of board game cards - Durable material for long gameplay - Acid free - no PVC"
display_price: "EUR2.95"
language: ""
last_updated: ""
merchant_category: "Spelonderdelen"
merchant_deep_link: "https://www.spellenrijk.nl/artikel/20343/blackfire-boardgame-sleeves-square-72x73mm.html?utm_source=affiliate4you-NL&utm_campaign=datafeed"
merchant_id: "12893"
merchant_image_url: "https://www.spellenrijk.nl/resize/18111_3wy7yf3_5638761353075.jpg/300/300/True/blackfire-boardgame-sleeves-square-72x73mm.jpg"
merchant_name: "Spellenrijk.nl NL - FamilyBlend"
merchant_product_id: "20343"
product_name: "Blackfire Boardgame Sleeves - Square (72x73mm)"
search_price: "2.95"
store_price: "2,95"

I want to get the price (store_price) from this JSON object and show this on my HTML site. Used the find and findIndex function but I constantly get a -1 returned.

The code I am using (based on this answer: Find object by id in an array of JavaScript objects):

    var product = "Blackfire Boardgame Sleeves - Square (72x73mm)";
    var price =  data.findIndex(x => x.products.product.product_name === product)