Unable to get the value of a Promise . Error “Property ‘Choices’ does not exist on type ‘Promise'” [duplicate]

I have the following type script inside my ReactJs SPFx sharepoint online web part:-

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  IPropertyPaneDropdownOption,
  PropertyPaneDropdown} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'ContactListWebPartStrings';
import ContactListApp from './components/ContactListApp';
import { IContactListProps } from './components/IContactListProps';
import { sp } from "@pnp/sp/presets/all";


export interface IContactListWebPartProps {
  department: string;
}

export default class ContactListWebPart extends BaseClientSideWebPart<IContactListWebPartProps> {
  private viewModeOptions: IPropertyPaneDropdownOption[] = null;
  public render(): void {
    const element: React.ReactElement<IContactListProps> = React.createElement(
      ContactListApp,
      {
        department: this.properties.department,
        context: this.context
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }
  public onInit(): Promise<void> {
    return super.onInit().then( _ => {
      sp.setup({
        spfxContext: this.context
      });
      const choice =  
      sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
      this.viewModeOptions = choice.Choices.map((choice: string, idx: number) => 
      {
        return {
         key: idx,
         text: choice
        }
      })
   });
  }


  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneDropdown('department', {
                  label: 'Department',
                  options: this.viewModeOptions,
                  selectedKey: this.viewModeOptions[0].key,
                  disabled: !this.viewModeOptions
                 }),
              ]
            }
          ]
        }
      ]
    };
  }
}

but i am getting this error on choice.Choices.map:-

Property ‘Choices’ does not exist on type ‘Promise’

here is my web part details:-

{
  "@microsoft/generator-sharepoint": {
    "isCreatingSolution": true,
    "environment": "spo",
    "version": "1.12.1",
    "libraryName": "contact-list-webpart",
    "libraryId": "aa3dbbd0-0d6b-4cae-98b0-c29c37998c6e",
    "packageManager": "npm",
    "isDomainIsolated": false,
    "componentType": "webpart"
  }
}

Variables from different scripts are getting overridden

I am learning javascript and made a project where I have two canvases where I draw circles on. The scripts for each canvas is in its own file in the same folder. My problem is that for both of these scripts I am using the same variable names eg. radius and they seem to be shared between the two scripts.

I declare the variables as follows in the beginning of the file and then the function right afterwards.

const radius = 23;
const motionTrailLength = 30;
var context;
var xPos, yPos, maxX, maxY;
var dx = 2;
var dy = 2;

function init(canvas) {...}

I read that let and const “declared inside a { } block cannot be accessed from outside the block” so is there some way can wrap the script in those blocks to stop them from getting overridden?

How to flip image in jquery if the animation is at 0% and 50%?

I am try to make a running santa in my project.

How to loop transform: scaleX(1) and transform: scaleX(-1) when the animation start in 0% an 50%?

setTimeout(function(){
  //Enter your stuff here
  $('.animation').css("transform", "scaleX(1)")
}, 7500);  
.animation img {
  max-width: 100%;
}

.animation {
  width: 50px;
  position: absolute;
  bottom: 0;
  animation: example 15s infinite; 
  padding: 5px 9px 1px 0;
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  transform: scaleX(-1)
}

@keyframes example {
  0%,
  100% {
    left: 0;  
    /* background: white; */
  }
  40% {
    /* background: green; */
  }
  30% {
    /* background: yellow; */
  }
  20% {
    /* background: orange; */
  }
  50% {
    left: 97%;  
    /* background: blue; */
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation">
  <img src="https://lh3.googleusercontent.com/pw/AM-JKLX6lpuXIUQzWYC8J9vlnsS9Cb9irs-2kPKBM9XaugC4iDCag2-7w-zC7BSQls0Ea51YewUFFSJquODLZ8PfaAoqelAXOlCKmh0H7Cn9G5HcwX_u2XNT_tvr8ZD5as6He3dpMrrVH_-ZCaG1xctS_Tei=s512-no" alt="run santa run">
</div>

Codepen link: demo

JSON image importing

I am trying to add 4 images on my site however the images are not loading. I can see 4 images in the inspector tool, however they are not showing up.

This is my code in JS:

function createZooland(zoolandData) {
    let content = document.getElementById("content");

let h2 = document.createElement("h2");
let h3 = document.createElement("h3");
let blockquote = document.createElement("blockquote");
let img = document.createElement("img");

h2.innerHTML = `${zoolandData[0].common_name}`;
content.appendChild(h2);

h3.innerHTML = `${zoolandData[0].scientific_name}`;
content.appendChild(h3);

blockquote.innerHTML = `${zoolandData[0].description}`; 
content.appendChild(blockquote);

for(let i = 0; i < zoolandData.length; i++){
    for(let j = 0; j < zoolandData[i].images["image"].length; j++){
        img.src = "images/" + `${zoolandData[0].images.image}`;
        

        content.appendChild(img);
    }
}

}

and this is the JSON it’s referencing:

{
            "common_name": "Koala",
            "scientific_name": "Phascolarctos cinereus",
            "description": "Koalas are well-known...",
            "images": {
                "image": [
                    "koala1.jpg",
                    "koala2.jpg",
                    "koala3.jpg",
                    "koala4.jpg"
                ]
            }
        },

Please let me know if any additional information is needed. I’m not sure how to get the images to display.

How do I paste text with Android clipboard manager in an empty input in a WebView?

We have a web page with an input element on a webview App on Android.

If the input text is not empty, has text, you can touch and the clipboard manager is launched and shows:
When clipboard is empty “select all”
When clipboard is full “paste, select all”

BUT, when the input text is empty you can not launch the clipboard manager in order to paste text.

Should I implement onLongClick on Android webview app? if yes, what is the code to simply launch the Android Clipboard Manager?

Should I add an html paste button and solve it with html code?

How to check whether a user exists in mongoose?

So, I am trying to check whether there is a user or not I have the following code:

const userExist = await User.find({ username: req.body.username });
if (userExist)
   return res.status(400).send({ message: "User already exists" });

but even if the user doesn’t exist it still gives the error User already exists and the userExists object return []

How to return an array with the step of the sum of the previous value?

How to return an array with the step of the sum of the previous value?

I have an input number that is 1000
I want to get [1000, 2000, 3000 … 10000]

I’m trying to:

  const range = (i: number, o: number) => {
    const arr = [0, 1, 2, 3, 4].reduce(
      (accumulator: any, currentValue: any, index: any, array: any) => {
        console.log((array[index] = accumulator + currentValue));
        return 1;
      },
      10000
    );
  };

  range(1000, 10000);

How Jsx is valid javascript?

I use react and jsx. my question is how jsx is a valid js syntax? only way that I think it’s maybe true, is that react compiles all the file and converts jsx(s) to valid js. like what C preprocessor does with macros. is it true? and if it is true, is it right that we consider react as js library? I think it is higher level of a library.

if No, who it is done?

How to consume a REST API properly on a multi page website

What is the best approach or best practice to consume a REST API within a multi-paged website on client side?

Lets assume I have the following REST API defined

/product -> all products, high level information 
/product/{id} -> detailed product information about product with given id

Further assume that my website has two .html pages, index.html and detail.html.

Inside the index.html I would query all products with high level information from my REST API with an AJAX call in Javascript. I then alter a table element inside the index.html page with the received JSON and display the high level information of each product inside this table.

Each table entry also has a link to the detailed product information, e.g. url/products/42.

Now to the interesting part. If I press the link of one specific product and want to show the detail.html page with detailed information about the pressed product id, how to I tell the Javascript inside detail.html which product the user pressed and is to be queried from the REST API?

I know how I perform these REST API calls in a native mobile app, since I always know, which element a user has pressed. I am a little bit lost how to do this on a multi paged website application.

Thanks to enrich my mind 🙂

How to get mapUrl of a spot knowing lat and lng of a spot? Using google-map-react library. Is there a library fixture or maybe google Api?

I have typescript + React app. I’m using google-map-react library. It’s very easy to use and I love it. So far I was able embed a map and put a custom dot on a map of specific location. What I want is by clicking on this dot get a direction to this spot on google maps. I don’t care if google map will open in a new tab and so on and so far. What I’m thinking is by knowing lat and lng generate a link of this specific spot and redirect to it. But how to generate this link ?

Is there a library fixture or maybe google Api ?

VueJS – i can’t hide readmore button before or after reach the selected limit data to show in vuejs

i’m using vuejs2. Try to hide the button before or after reach the amount of value, but i can’t event get the data length to compare with limit. I try to re-assign it into an array, still not work cause the length is 1. Any idea how to do or different way to do that? Thanks

export default {
  name: 'SlideEvents',
  props: {
    dataEvents: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      limit: 6
    }
  },
  components: {
    CardSlide
  },
  computed: {
    dataFilter () {
      if (this.dataEvents) {
        return this.dataEvents.slice(0, this.limit)
      } else {
        return this.dataEvents
      }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div class="container-fluid more-top">
    <div class="row">
      <div class="col-md-12">
        <div class="card box-simple border-0">
          <h2>Agenda Terbaru</h2>
          <div class="mt-5 mb-5">
            <div class="row row-cols-1 row-cols-md-3 g-5 mt-2 px-4">
            
              <CardSlide class="mb-4" v-for="each in dataFilter"
              :key="each.id"
              :content="each" />
            </div>
            <button @click="limit*=2">Show More</button>
          </div>
        </div>
      </div>
    </div>
  </div>

Trying to edit row’s in a HTML table using react.js

I have built a table in which user enter’s values in first three Cols and next four get’s calculated. Till here it is working Fine but when I change a respective value in a Col the corresponding Col’s calculated value does not change and the problem which arises after deleting is the row get’s deleted but it’s value shift’s in the below row

  const row1 = [];
  const [row, setRow] = useState();
  const [NewRow2, setNewRow2] = useState([0, 1, 2, 3, 4]);
  const [allRowsAdded, updateAllRows] = useState(5);

  const [IntensificationRatio, setIntensificationRatio] = useState()

  const [editFormData, setEditFormData] = useState({
    Injection_Speed: "",
    Fill_Time: "",
    Peak_Inj_Press: "",
    Viscosity: "",
    Shear_Rate: ""
  })

  const [isRowId, setIsRowId] = useState(null)

  const handleEditFormChange = (event) => {
    event.preventDefault();
    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;
    const newFormData = { ...editFormData };
    newFormData[fieldName] = fieldValue;
    setEditFormData(newFormData);
  }

  const handleEditFormSubmit = (event) => {
    event.preventDefault();
    const editedValue = {
      id: isRowId,
      Injection_Speed: editFormData.Injection_Speed,
      Fill_Time: editFormData.Fill_Time,
      Peak_Inj_Press: editFormData.Peak_Inj_Press,
      Viscosity: editFormData.Fill_Time * editFormData.Peak_Inj_Press * IntensificationRatio,
      Shear_Rate: 1 / editFormData.Fill_Time,
    }
    const newValues = [...NewRow2];
    const index = NewRow2.findIndex((value) => value === isRowId)
    newValues[index] = editedValue;
    setNewRow2(newValues);
    console.log(newValues)

  }

In this part of code “row1” array and “row” variable is to serve the purpose of increasing row’s as per user’s need. “NewRow2” is the actual array using which row’s are created and values are entered in them. “allRowsAdded” is to keep the track of row’s getting added so that the “id” doesn’t clash. The “IntensificationRatio” is needed to Calculate Viscosity as you can see in the ” handleEditFormSubmit” function.

<tr key={rowId} onClick={() => setId(rowId)}>

<td> {rowId} </td>

<td> <input type='text' className="form-control" defaultValue={NewRow2[rowId].Injection_Speed} name="Injection_Speed" onChange={handleEditFormChange} /> </td>

<td> <input type='text' className="form-control" defaultValue={NewRow2[rowId].Fill_Time} name="Fill_Time" onChange={handleEditFormChange} /></td>

<td><input type='text' className="form-control" defaultValue={NewRow2[rowId].Peak_Inj_Press} name="Peak_Inj_Press" onChange={handleEditFormChange} /> </td>

<td> <input type='text' className="form-control" name="Viscosity" value={isNaN(Math.round(element.Viscosity)) ? '-' : Math.round(element.Viscosity)} readOnly /> </td>

<td>  <input type='text' className="form-control" name="Shear_Rate" value={isNaN(Number(element.Shear_Rate)) ? '-' : Number(element.Shear_Rate).toFixed(3)} readOnly /> </td>

<td> <input type='text' name="Absolute_Viscosity" value={rowId === 0 ? '-' : (isNaN(Math.round(NewRow2[rowId - 1].Viscosity - NewRow2[rowId].Viscosity)) ? '-' : Math.round(NewRow2[rowId - 1].Viscosity - NewRow2[rowId].Viscosity))} className="form-control" readOnly /></td>

<td> <input type='text' name="Drop_Viscosity" value={rowId === 0 ? '-' : (isNaN(Number(((NewRow2[rowId - 1].Viscosity - NewRow2[rowId].Viscosity) * 100) / (NewRow2[rowId - 1].Viscosity))) ? '-' : (Number(((NewRow2[rowId - 1].Viscosity - NewRow2[rowId].Viscosity) * 100) / (NewRow2[rowId - 1].Viscosity))).toFixed(1))} className="form-control" readOnly /></td>

<td> <i className="fa fa-trash viscocity_icons" onClick={() => deleteRow2(element)}></i> </td>
</tr>

This is the Table Row with Table data’s 1st Three input field’s are editable and hence contain a “onChange” and the rest 4 are readOnly.
What changes should i make so that i can edit and delete.

CodeSandBox Link :

https://codesandbox.io/s/solitary-architecture-zur17?file=/src/App.js:77-111