How to save fetched data to a variable [duplicate]

I am trying to fetch some data from a remote API, filter it and later display it, when I console.log it I see that it is present, however, I can’t figure out how to save the data in a variable once fetched, how can I do it? Here is my attempt:

  let newData = null

   const fetchedData = fetch('https://jsonplaceholder.typicode.com/posts')
     .then((response) => response.json())
      .then((json) => newData(json));


const orderEmployees = newData.filter(employee => employee.jobTitle === 'Sales Representative');
const initialFilterState = { };

orderEmployees.forEach(employee => {
    if(employee.fullName === 'Wait Peperell') {
        initialFilterState[employee.id] = false;
    } else {
        initialFilterState[employee.id] = true;
    }
});

Validate submit button not working in jquery

I am beginner web developer.
I have webpage with dynamic create search forms:

<form action="{{ pageTemplate.pageHeader.webUrl |raw }}ListaStron/Wszystkie" method="get" name="contactformXX" aria-hidden="false"
                      class="form validate clearfix validate-formX clickForm validate-formXXX1">
                    <div class="form-group ">
                        <div class="form-group has-feedback ">
                            <input required="required" name="query" type="text" class="form-control indexInputSzukaj input_id1"
                                   id="input_id1"
                                   placeholder="Znajdź" value="{{ pageTemplate.pageHeader.pageValue.searchQuery }}"/>
                                   
<button type="submit" class="form-control-feedbackXX glyphiconColor showActionAfterClick searchBtnSUbmit1" style="background-color: transparent;border: 0;top:2px" >
   <span class="glyphicon glyphicon-search"></span>
</button>


                        </div>
                    </div>
                </form>

Sometimes I have 1 or more this form on one view.

I have validate code:

$('.searchBtnSUbmit1').click(function (e) {
    e.preventDefault();

    $('#.validate-formXXX1 input[type="text"]').blur(function () {
        alert('1');
        if (document.getElementsByClassName("input_id1").value.length == 0) {
            e.preventDefault();
            alert('Proszę uzupełnić poprawnie wszystkie wymagane pola formularza!');
        } else {
            form.submit();
        }
    });
});

But it’s not working 🙁 How can I repair it?

vue-apollo – Property ‘value’ does not exist on type ‘Readonly<Ref<Readonly>>’

THE SITUATION:

I am trying to integrate vue-apollo v4 with Typescript.

I am fetching a simple query using useQuery and useResult.

useResult by default return this type: Readonly<Ref<Readonly<any>>>

THE CODE:

import { GET_COUNTRY } from '../graphql/queries'
import { Country } from '../types'

setup() {
  const route = useRoute()
  const code = route.params.code

  const { result, loading } = useQuery(GET_COUNTRY, {code: code}, { 
    clientId: 'default', 
    fetchPolicy: 'cache-first'
  });
  const country = useResult(result, {}, (data) => data.country);

  console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

  return {
    country,
    loading
  }
}

ATTEMPT 1:

const country: Country = useResult(result, {}, (data) => data.country);
// Type 'Readonly<Ref<Readonly<any>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

ATTEMPT 2:

const country = useResult(result, {}, (data) => data.country as Country);
console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

ATTEMPT 3:

const country: Country = useResult(result, {}, (data) => data.country as Country);
// Type 'Readonly<Ref<Readonly<Country | {}>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

THE QUESTION:

Is it possible to combine useResult with my own Typescript interface?

How to read configuration files and map them to typesafe models using Vue3?

I have a Vue3 app using TypeScript and want to load a configuration file and map it to a model.

Inside the public directory I added a subdirectory configurations with a config.json file

{
    "foo": "bar"
}

This json object should get mapped to the following model config.ts

export interface Config {
  foo: number;
}

Inside my Vue component I’m reading the configuration file from the public folder and try to map it to the model

<script lang="ts">
import { defineComponent } from "vue";
import { Config } from "./config";

export default defineComponent({
  setup() {
    fetch(process.env.BASE_URL + "configurations/config.json")
      .then((response: Response) => response.json())
      .then((jsonConfiguration: any) => {
        const config: Config = jsonConfiguration as Config;
        console.log(config.foo);
      });
  },
});
</script>

I would expect an exception, e.g.

“foo must be of type number”

but the logger simply logs “bar”, although it’s not a number.

What is a common (and typesafe) approach to

  • Put configuration files somewhere during deployment (e.g. customer config)
  • Read them
  • Map the content to a given model

using Vue3?

How to solve realm already opened on current thread with different schema?

What I’m trying to do is save a table and his following fields , but these table’s are defined by an API response and the fields are predeterminated, but I cannot figure out how to make it works properlly since the table is variable, I will show you some code:

Here is my model where I call the realm to open my table , as you can see there is a variable called table and this is where I send a string which is the name of the table that I want to open.

export const getRealm = async(table) => {
  const tabela = {
    name: table,
    properties: {
      field: "string",
      fieldtype: "string",
    }
  }
  try {
    return await Realm.open(
      {
        schema: [tabela],
        deleteRealmIfMigrationNeeded: true,
      }
    );
  } catch (error) {     
    console.log('ERRRRROOOOOOOR REALM',error.message);
  }
};

When I want to store some data into my realm, with the controller realmAction.js , my dados is a JSON and my objeto is the name of the table which is a string

export const FieldsSchema = async (dados,objeto) => { 
  try {  
    dados.map(
      async (item) => {
      await getRealm(objeto).then((realm) => {      
        const data = {
        field: item.field,
        fieldtype: item.fieldtype,
       };
        realm.write(() => {
        realm.create(objeto, data, 'modified'); 
        });
       // realm.close(); Closing results me in an error which is `Cannot access realm that has been closed` cause its a map function and send more than once the same table string
      });
      }
    )  
  } catch (error) {
    console.log('ERROOOR', error.message);
  }
};

What seems to be wrong is that realm cannot handle oppening two different tables in the same thread , but as I read in the mongo/realm documentation I need to seet a model schema , but my models are a variable which the users create , someone knows how can I handle this ?

Using local storage on Angular

I would appreciate someone’s help or opinion regarding a little problem I have since I am complete beginner in coding.
I am trying to make a simple phonebook using Angular, but I am having a bit hard time making my “app” store the information inserted to local storage.
Here is what I have so far, so if anyone has time to take a peak, I would appreciate it very much.
Kind regards 🙂

File input still required after upload

I have a file input which is required. I attach a file to it, submit the form, go back on the form and here is the problem. Instead of showing me the uploaded filename in the input, it’s just an empty input, so I have to fill it again as it’s a required input (otherwise I cannot submit the form).
Is there a way to “retrieve” the file and attach it to the input?

Thank you.

why is useMatch not working in React router?

I’m learning how to use useMatch() from "react-router-dom"
I am getting the error below and my web page is blank:

Uncaught TypeError: Cannot read properties of undefined (reading 'path')
    at matchPath (index.tsx:1148)
    at index.tsx:481
    at mountMemo (react-dom.development.js:15846)
    at Object.useMemo (react-dom.development.js:16219)
    at useMemo (react.development.js:1532)
    at useMatch (index.tsx:481)
    at About (About.js:7)
    at renderWithHooks (react-dom.development.js:14985)
    at mountIndeterminateComponent (react-dom.development.js:17811)
    at beginWork (react-dom.development.js:19049)

my code is below

import React from "react"
import { useMatch  } from "react-router-dom"
import { Link, Route } from "react-router-dom"
import SinglePage from "./SinglePage"

const About = () => {
  const { url, path } = useMatch()
  console.log("hello usematch!", useMatch())
  return (
    <div>
      <ul>
        <li>
          <Link to={`${url}/about-app`}>About App</Link>
        </li>
        <li>
          <Link to={`${url}/about-author`}>About Author</Link>
        </li>
      </ul>
      <Route path={`${path}/:slug`}>
        <SinglePage />
      </Route>
    </div>
  )
}
export default About

I’ve tried going through the api docs but unclear about why this is not working and how to make the page load. I am trying to return the nearest current route match within the context of where it’s called.

I am quite new to react and router apis.

Thanks so much

How to make a function work for multiple div’s with the same classes in javascript?

I’ve been trying to make a web-based tallying-application using javascript. I got it to work, but only for the first instance of a class (e.g. first tallying-element).

How do I make the function work for multiple the subsequent instances of the tallying-elements?

Also, I’m using Bootstrap v5.1.3 for the css, but did not add the lengthy code.

Your help is greatly appreciated!

let add = document.querySelector(".add");
let minus = document.querySelector(".minus");
let reset = document.querySelector(".reset");
let counter = document.querySelector(".counter");

add.addEventListener('click', addCounter);
minus.addEventListener('click', minusCounter);
reset.addEventListener('click', resetCounter);



function addCounter(item) {
    counter_num = counter.innerHTML
    counter.innerHTML = parseInt(counter_num) + 1
}

function minusCounter(){
    counter_num = counter.innerHTML
    if (counter_num == 0){
        return false
    }
    counter.innerHTML = parseInt(counter_num) - 1
}

function resetCounter(){
    if (counter.innerHTML == 0){
        return false
    }
    if (confirm("Weet je zeker dat je de telling wilt resetten?") == true){
        counter.innerHTML = 0;
        resetCounter = "De telling is gereset!"
    } else {}
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta  name="viewport" content="width=devide-width", initial-scale="1.0">
        <link rel="stylesheet" href="bootstrap.min.css">
        <title>Turf-app geadresseerd voorschrijven</title>

        <style>
            .counter{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}
            .tally_container{background-color:lightgrey; border-radius: 10px; padding:20px;}
            .add{width: 38px; height: 38px;}
            .minus{width: 38px; height: 38px;}
            .title-text{color: white;}
            .counter2{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}

        </style>
    </head>

    <body class="jumbotron bg-dark">
        <h1 class="text-center mx-4 mt-4 mb-5 title-text">Turf-app geadresseerd voorschrijven</h1>
        
        <div class="container" id="1">
            <div class="tally_container mt-3 mb-3" name="tally-element">
                <div class="vraag-container mb-3">
                    <h3>Patiënten zonder recept</h3>
                </div>

                <div class="counter-div text-center">
                    <div class="mx-2 text-center mb-2 counter bg-dark">0</div>
                </div>

                <div class="buttons">
                    <button class="btn btn-success mx-2 add">+</button>
                    <button class="btn btn-danger mx-2 minus">-</button> <br>
                    <button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
                </div>
            </div>
        </div>

        <div class="container" id="2">
            <div class="tally_container mt-3 mb-3" name="tally-element">
                <div class="vraag-container mb-3">
                    <h3>No-shows</h3>
                </div>

                <div class="counter-div text-center">
                    <div class="mx-2 text-center mb-2 counter bg-dark">0</div>
                </div>

                <div class="buttons">
                    <button class="btn btn-success mx-2 add">+</button>
                    <button class="btn btn-danger mx-2 minus">-</button> <br>
                    <button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
                </div>
            </div>
        </div>

     
        
        
    <script src="app.js"></script>
    </body>

</html>

Right way to iterate over record [duplicate]

I’m trying –

export function logError(paramsToLog?: Record<string, string>): void {
    const logData: LoggerData[] = [];
    if (paramsToLog) {
        for (const key of paramsToLog) {
            logData.push(LoggerData.create(key, paramsToLog[key]));
        }
    }
    ....
}

I see eslint complaining – (parameter) paramsToLog: Record<string, string> Type 'Record<string, string>' must have a '[Symbol.iterator]()' method that returns an iterator.

Could not find any iterator in record arg.

react-image-annotate – How to save an image along with the annotations?

The npm package react-image-annotate gives a decent react component to annotate images.

This component uses a tag called <ReactImageAnnotate /> for the annotate window. It has a prop called onExit which will give the details of all the data of that image we are working on.

My question is:
Suppose I did mark some things using a box in the image, and now I want to save/export/download that image along with that box. How can we do that?

OIDC client silent refresh multiple times

Here is my client config:

const settings = {
      userStore: new WebStorageStateStore({ store: window.localStorage }),
      client_id: 'authtest',
      automaticSilentRenew: true,
      accessTokenExpiringNotificationTime: 10,
      response_type: 'code',
      scope: 'openid profile email offline_access',
    };

Silent refresh page is a static html page

<!DOCTYPE html>
<html>
  <head>
    <title>Silent Renew Token</title>
  </head>
  <body>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.11.5/oidc-client.min.js"
      integrity="sha512-pGtU1n/6GJ8fu6bjYVGIOT9Dphaw5IWPwVlqkpvVgqBxFkvdNbytUh0H8AP15NYF777P4D3XEeA/uDWFCpSQ1g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script>
      console.log('renewing tokens');
      new Oidc.UserManager({
        userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
      }).signinSilentCallback();
    </script>
  </body>
</html>

I wanted to check how exactly it works and there is something strange:
token request is being sent multiple times (6x)

Is this supposed to work like that? My [PersistedGrant] table is growing very fast during this test (6 records every 50 seconds). What is the problem and how to solve it?

removing an element in array within map in react

On the click of the span, i want to remove that element from the array and run the map again so that the spans also gets removed. I don’t know if the syntax is wrong or what. This is the link to sandbox where I wrote my code. https://codesandbox.io/s/angry-wu-4dd11?file=/src/App.js

import "./styles.css";

export default function App() {
  const data = [{
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
    {
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
  ];

  return ( <
    div className = "App" > {
      data.map(function(val, id) {
        return ( <
          span key = {
            id
          }
          className = "select__item"
          onClick = {
            (e) => {
              data.splice(data.indexOf(val), id + 1);
              console.log(data);
            }
          } >
          {
            val.name
          } < br / > < br / >
          <
          /span>
        );
      })
    } <
    /div>
  );
}

How do you add toggle functionality to a wishlist button to add and remove items from a wishlist?

I have made a wishlist where I add items to a wishlist by a button and remove the items from within the wishlist itself by pressing a cross next to the item. However, I need the button to add AND remove items too by having a toggle functionality on the button itself. Can anybody help?

$(document).ready(function() {
      $(".wishlist").on("click", function() {
        $data = "";
        $item_id = $(this).attr("item_id");
        $item_name = $(this).attr("item_name");
        $item_str = "<tr class='wishlist-item' id='list_id_" + $item_id + "'><td class='w-pname'>" + $item_name + "</td><td class='w-premove' wpid='" + $item_id + "'>x</td></tr>";
        //check if the element is in the array
        if ($.inArray($item_id, wish_list) == -1) {


          $("#wish_list_item").append($item_str);

          wish_list.push($item_str);
          localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
          show_message($item_name + " Item Added");
        }
        count_items_in_wishlist_update();
      });