Importing a key of an export in es6 - ecmascript-6

In def.js:
export const defs = {
name: 'Joe',
age: 30,
id: 123
}
In user.js:
import { defs } from './def';
const { name } = defs;
console.log(name);
Is there a way to import defs.name right away, without importing defs first?
Something like:
import {defs.name} from './defs';

Related

Properties "missing" from type definitions for schemas for Sanity

I'm using Sanity in a project and came across an error when I tried to pass props to a component
that says: "Type 'Card[]' is missing the following properties from type 'Card': _type, title, image, description, and 4 more." Card in this context is one of my schemas for Sanity that I created. When I run my web app, I also get: "SyntaxError: Unexpected token < in JSON at position 0" I'm trying to figure out why my fetching data won't work.
I've checked my type definition file, my fetch functions etc to make sure that everything connected correctly and and I didn't have any spelling or importing errors. I've also tried restarting my server. At the bottom of my index page, i'm using a getStaticProps async function. When I comment it out, my app runs, so the problem has something to do with that.
my code:
Index:
import type { GetStaticProps} from 'next';
import Head from 'next/head'
import Image from 'next/image'
import React from 'react'
import Header from 'components/Header'
import Hero from 'components/Hero'
import Middle from 'components/Middle'
import Chapters from 'components/Chapters'
import Footer from 'components/Footer'
import {Card, CardList, Chapter, Banner, Pages, Summary, SlideCard} from "typings"
import { fetchCard} from 'utils/fetchCard'
import { fetchCardList} from 'utils/fetchCardList'
import {fetchChapter} from 'utils/fetchChapter'
import {fetchBanner} from 'utils/fetchBanner'
import { fetchPages} from 'utils/fetchPages'
import { fetchSummary} from 'utils/fetchSummary'
import { fetchSlideCard} from 'utils/fetchSlideCard'
type Props = {
card: Card[];
cardList: CardList[];
chapter: Chapter[];
banner: Banner[];
pages: Pages[];
summary: Summary[];
slideCard: SlideCard[];
}
export default function Home({card, cardList, chapter, banner, pages, summary, slideCard}: Props ) {
return (
<>
<Head>
<title>Shonen Jump Plus 2</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="max-w-screen-2xl mx-auto">
<div>
<Header />
<Hero card={card}/>
<Middle />
<Chapters />
<Footer />
{/* Hero Slides */}
{/* Four Featured */}
{/* Latest Chapters */}
</div>
</main>
</>
)
}
export const getStaticProps: GetStaticProps<Props> = async () => {
const card: Card[] = await fetchCard();
const cardList: CardList[] = await fetchCardList();
const chapter: Chapter[] = await fetchChapter();
const banner: Banner[] = await fetchBanner();
const pages: Pages[] = await fetchPages();
const slideCard: SlideCard[] = await fetchSlideCard();
const summary: Summary[] = await fetchSummary();
return {
props: {
card,
cardList,
chapter,
banner,
pages,
slideCard,
summary,
},
revalidate: 2,
};
};
Type Definitions:
interface SanityBody {
_createdAt: string;
_id: string;
_rev: string;
_updatedAt: string;
}
export interface Image extends SanityBody {
_type:"image";
asset: {
_ref: string;
_type: "reference"
};
}
export interface Card extends SanityBody {
_type: "card";
title: string;
image: Image;
description:Text;
}
export interface Banner extends SanityBody {
_type: "banner";
title: string;
image: Image;
}
export interface Pages extends SanityBody {
_type: "pages"
page1: Image;
}
export interface CardList extends SanityBody {
_type: "cardList"
thumbnail:Image;
title:string;
author:string;
chapter:string;
subtitle:string;
date:string;
}
export interface SlideCard extends SanityBody {
_type: "slideCard"
image:Image;
title:string;
chapter:string;
}
export interface Summary extends SanityBody {
_type: "summary"
title:string;
author:string;
description:Text;
}
export interface Chapter extends SanityBody {
_type: "chapter"
title:string;
date:string;
}
card schema:
export default {
name: 'card',
title: 'Card',
type: 'document',
fields: [
{
name: 'thumbnail',
title: 'Thumbnail',
type: 'image',
},
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'description',
title: 'Description',
type: 'text',
},
],
}
getCard:
fetching data on the front-end
//Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {groq} from "next-sanity";
import {sanityClient} from "sanity";
import { Card } from "typings";
const query = groq`
*[_type == "card"]
`
type Data = {
card: Card[];
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const card: Card[] = await sanityClient.fetch(query);
res.status(200).json({ card })
}
fetchCard:
fetching data on the back-end
import {Card} from "typings";
export const fetchCard = async() => {
const res = await fetch (`${process.env.NEXT_PUBLIC_BASE_URL}/api/getCard`);
const data = await res.json();
const card: Card[] = data.card;
return card;
};

implementing tagbox widget in functional components

i have been working on creating surveyjs form in reactjs using functional components.Everything else fits perfectly but the issue is regarding restfull tagBox widgets.
there is a good example to use it in class component https://codesandbox.io/s/ljnh1, but i'm having difficulties to convert it into functional component.
any help from your end will be great
Thanks
You can move all the static initializations outside the component:
import React, { Component } from "react";
import $ from "jquery";
import select2Init from "select2";
import "select2/dist/css/select2.min.css";
import * as Survey from "survey-react";
import * as widgets from "surveyjs-widgets";
import "survey-react/modern.css";
import "./index.css";
Survey.StylesManager.applyTheme("modern");
window["$"] = window["jQuery"] = $;
select2Init();
widgets.select2(Survey);
widgets.select2tagbox(Survey);
class SurveyComponent extends Component {
render() {
const json = {
elements: [
{
type: "tagbox",
isRequired: true,
choicesByUrl: {
url: "https://restcountries.eu/rest/v2/all"
},
name: "countries",
title:
"Please select all countries you have been for the last 3 years."
}
]
};
const survey = new Survey.Model(json);
return <Survey.Survey model={survey} />;
}
}
export default SurveyComponent;
And thus you'll get the only render function left in your class.
Here is your forked plunker - https://codesandbox.io/s/new-brook-wsmot?file=/src/SurveyComponent.jsx
Update 1
Functional component
import React, { Component } from "react";
import $ from "jquery";
import select2Init from "select2";
import "select2/dist/css/select2.min.css";
import * as Survey from "survey-react";
import * as widgets from "surveyjs-widgets";
import "survey-react/modern.css";
import "./index.css";
Survey.StylesManager.applyTheme("modern");
window["$"] = window["jQuery"] = $;
select2Init();
widgets.select2(Survey);
widgets.select2tagbox(Survey);
function render() {
const json = {
elements: [
{
type: "tagbox",
isRequired: true,
choicesByUrl: {
url: "https://restcountries.eu/rest/v2/all"
},
name: "countries",
title: "Please select all countries you have been for the last 3 years."
}
]
};
const survey = new Survey.Model(json);
return <Survey.Survey model={survey} />;
}
export default render;
Here is the updated code sandbox - https://codesandbox.io/s/crazy-elgamal-01nku?file=/src/SurveyComponent.jsx
And of course - survey model should be passed as a prop value

Json Object Ref in other json Object

I am developing an static website with angular, we've decided to put data in JSON files. But data is quite large and repetitive in nature.
So, I've decided to segregate data in multiple JSON files.
Like
foo.json
{ name: 'Avinash', Age: 88 }
Woo.json
{ City: 'Newyork', Street: 'Lincoln Park' }
Soo.Json
{City: 'Dubai', Street: "Marina"}
Loo.Json
{ Customer: 'foo.json', Address1: 'Woo.json', Address2: 'Soo.Json' }
It should compile all objects to gether on retrieval.
I've read json pointers concept here, thought it might be useful. But I don't know how to do it in Typescript...
Instead of json files, create ts files and export const from there. Something like this:
foo.ts
export const foo = { name: 'Avinash', Age: 88 };
woo.ts
export const woo = { City: 'Newyork', Street: 'Lincoln Park' };
soo.ts
export const soo = {City: 'Dubai', Street: "Marina"};
loo.ts
import { foo } from './foo';
import { woo } from './woo';
import { soo } from './soo';
export const loo = { Customer: foo, Address1: woo, Address2: soo };
loo will contain an aggregated object that you can then import and use in the Component you want.
Something like this:
import { Component } from '#angular/core';
import { loo } from './data/loo';
#Component({...})
export class AppComponent {
ngOnInit() {
console.log(loo);
}
}

Export Json data to an excel file using Angular 4

I have an Array List of objects. I want to export those data to an Excel file (.xlsx or .xls).
The template of the Excel file is also given. What needs to be done is only mapping to an existing Excel file. The Excel file is located in the Angular project itself. How can I achieve this using Angular 4.
[
{
"name": "Roshan",
"age": "35"
},
{
"name": "Ritika",
"age": "29"
}
]
The above data should be map to an Excel of having column names are Employee_Name and Employee_age.
try xlsx package
install xlsx to your project
npm install xlsx --save
import { Injectable } from '#angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
#Injectable()
export class ExcelExportService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + EXCEL_EXTENSION);
}
}
export class AppComponent {
name = 'Angular 6';
data: any = [{
eid: 'e101',
ename: 'ravi',
esal: 1000
},
{
eid: 'e102',
ename: 'ram',
esal: 2000
},
{
eid: 'e103',
ename: 'rajesh',
esal: 3000
}];
constructor(private excelService:ExcelExportService ){
}
exportAsXLSX():void {
this.excelService.exportAsExcelFile(this.data, 'sample');
}
}
You can export multiple sheets to an excel file using this code. First I created a service file and created a method exportAsExcelFile() This method code is included below. fileInfo is the object that I am including in the code section.
#Injectable({
providedIn: 'root'
})
export class ExcelExportServiceService {
constructor() { }
public exportAsExcelFile(fileInfo: ExportFileInfo): void {
const workbook: XLSX.WorkBook = XLSX.utils.book_new();
fileInfo.templates.forEach((x)=>{
XLSX.utils.book_append_sheet(workbook,
XLSX.utils.json_to_sheet(x.data), x.sheetName);
});
XLSX.writeFile(
wb,
`${fileInfo.fileName}`
);
}
export interface ExportFileInfo{
fileName:string;
templates:ExportTemplateInfo[];
}
export interface ExportTemplateInfo{
data:any;
sheetName:string;
}
constructor(private exportService: ExcelExportServiceService) {}
excelFileExportFromJson(){
let data:any[]=[];
this.analysisDrugList.forEach(x=>{
data.push({
'NDC-9':x.ndc.substring(0,9),
'Canister':x.drawerType==='Smart'?'SMART':x.canisterLocation,
'Drug Name':x.name,
'Strength':x.strength,
'Manufacturer':x.manufacturer,
'NDC-11':x.ndc,
'CustomerNDC':x.customerDrugNdc,
'CItem#':x.atpCanisterNumber,
})
})
this.fileInfo={
fileName: `test_file_name.xlsx`,
templates:[{
data:data,
sheetName:`test_sheet`
}]}
this.exportService.exportAsExcelFile(this.fileInfo);
}

using json typescript, export a typed object

I want to export a typed object, of a json, to avoid using any as a type. But Im not sure how to create the d.ts file and use it in my project. My json uses platform, brand, locale, environment. This is what i have tried so far.
myjson.json
"desktop": {
"brandname": {
"eu": {
"a": "www.url.com",
"b": "www.otherurl.com",
}
}
}
myjson.d.ts
export class EnvUrlMap {
environment: string;
}
export class LocaleEnvMap {
locale: EnvUrlMap;
}
export class BrandLocaleMap {
brand: LocaleEnvMap;
}
export class PlatformBrandMap {
"desktop": BrandLocaleMap;
"mobile": BrandLocaleMap;
}
export {PlatformBrandMap as map};
index.ts
import map = require('my.json');
export {map};
PROJECT
main.ts
import { map } from 'my-project';
const config = (map as Map); `- ?? what is the type here ? Error cannot find Map`