How am I exporting my object incorrectly? - javascript

I'd like to know how I'm exporting my object incorrectly? In my view, I'm seeing this error: ./src/context.js
Attempted import error: 'detailProduct' is not exported from './data'.
In the console I indeed see the objects being populated correctly but for some reason it won't render my view because of the aforementioned error. What am I doing wrong?
export const storeProducts = [
{
id: 1,
title: "Crusk Beanie (black)",
img: "img/CruskipBlackBeanie.png",
price: 1,
company: "Cruskip",
info:
"Winter's right around the corner, get your beanie today!",
inCart: false,
count: 0,
total: 0
},
{
id: 3,
title: "Cruskip Short Sleeve T-shirt",
img: "img/CruskipWhiteShortSleeve.jpg",
price: 8,
company: "Cruskip",
info:
"Exclusive Cruskip white t-shirts!",
inCart: false,
count: 0,
total: 0
},
];
let detailProduct = {};
storeProducts.forEach((arrayItem) => {
detailProduct = {
id: arrayItem.id,
title: arrayItem.title,
img: arrayItem.img,
price: arrayItem.price,
company: arrayItem.company,
info: arrayItem.info,
inCart: arrayItem.inCart,
count: arrayItem.count,
total: arrayItem.total
};
console.log(arrayItem);
});
export default detailProduct;

You're likely importing it using braces, but you can't do that for default exports:
// This will work
import detailProduct from './data';
// This won't
import { detailProduct } from '.data';
On the other hand, since storeProducts is a named export, it works the other way around:
// This will work
import { storeProducts } from './data';
// This won't
import storeProducts from './data';

Related

Reactivity in props in Vue3 Composition API?

I'm watching a couple of props on a child component (basicSalaryMin and basicSalaryMax). When the value changes I'm then trying to update a reactive the value on the parent component (data.companyModels which is also passed to the child component as a prop inside allReactiveData).
Child component:
<template>
<div>
{{allReactiveData.companyModels}} // all data is rendered!
</div>
</template>
<script>
import { toRefs, watch, ref, reactive } from "vue";
export default {
name: 'SimPrivate',
props: {
reactiveData: {
required: true,
type: Object
},
},
setup (props, { emit }) {
const allReactiveData = ref(props.reactiveData);
const basicsalaryMin = ref(props.reactiveData.basicsalaryMin);
const basicsalaryMax = ref(props.reactiveData.basicsalaryMax);
const changeCompanyProfit = ref(props.changeCompanyProfit)
watch([basicsalaryMin, basicsalaryMax], ([newBSMin, newBSMax], [prevBSMin, prevBSMax]) =>
{
let wagesArray =[]
wagesArray.push(newBSMin, newBSMax);
adjustAllWorkersSalaries(wagesArray);
allReactiveData.companyModels.forEach(function(company)
//console is saying Uncaught (in promise) TypeError:
Cannot read property 'forEach' of undefined!!
and Can't do anything to the object from this point forward
I then need to add new sub-properties depending on
how many __ranks__ the property companyModel has...
but I'll get to that later
{
for (const [key, value] of Object.entries(company)) {
if (key === 'ranks') {
// if 1 rank add sub-object to companyModel.wages with var basicsalaryMin value called "wages: {1: basicsalaryMin}"
// if 2 ranks add sub-object: "wages:{1: basicsalaryMin, 2: basicsalaryMax }
// if 3 ranks add sub object: "wages...
// as in the model bellow but allowing for more levels
}
}
})
})
return {
allReactiveData,
basicsalaryMin,
basicsalaryMax,
}
}'
Parent component:
<template>
<div>
<input #change="handleMaxSalaries(basicsalaryMax)" id="maxsalaryInput" v-model.number='basicsalaryMax'>
<SimPrivate :reactiveData='reactiveData' #adjustAllWorkersSalaries='adjustAllWorkersSalaries'/>
</div>
</template>
<script>
</script>
import { toRefs, watch, ref, reactive } from "vue";
import SimPrivate from '../views/SimPrivate.vue'
export default {
name: "Simulator",
components: {
Slider,
SimPrivate
},
props: {},
setup( props, {emit}) {
let data = reactive({
avrgProfit: 0,
basicsalaryMin: 3000,
basicsalaryMax: 5000,
TotalUBICreatedPerMonth: 0,
companyModels: [
{ id: 'Big', workers: 250, ranks: 5, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000', 2: '3500', 3:'4000', 4: '4500', 5: '5000' }},
{ id: 'Medium', workers: 75, ranks: 3, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000', 2: '4000', 3:'5000' }},
{ id: 'Small', workers: 10, ranks: 2, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000', 2: '5000' }},
{ id: 'Individual', workers: 1, ranks: 1, companyAvrgProfit: 0, totalWages: Number, wages: {1: '3000'}}}
],
)}
let reactiveData = toRefs(data)
return {
allReactiveData,
basicsalaryMin,
basicsalaryMax,
}
)}
The goal is to then check the value of ranks (which will vary between 1 and 100) and create as many equidistant wage values as needed to match the rank number.
Any thoughts?
If you want to access or modify a ref from your script you need to do
yourref.value.
e.g.
yourref.value = 'Hello'
console.log(yourref.value)
// outputs : 'Hello'
So in your case allReactiveData.value
See docs

Vue property or method is not defined on the instance but referenced during render?

When trying this code in an online compiler it works fine
but on localhost I see this problem:
Property or method "searchfunc" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components)
main.js
var Hotels = [
{ name: "Sham", city: "Damascus", bed: 1, price: 100, id: "h1" },
{ name: "Shahbaa", city: "Aleppo", bed: 3, price: 200, id: "h2" },
{ name: "abcd", city: "Homs", bed: 5, price: 350, id: "h3" },
];
new Vue({
router,
store,
render: (h) => h(App),
searchs:'',
Hotels,
computed: {
searchfunc() {
return this.Hotels.filter((srh) => {
return srh.price >= parseInt(this.searchs);
});
}
}
}).$mount("#app");
Home.vue
<template>
<div class="home">
<form>
<input
type="text"
v-model="searchs"
placeholder="Search.."
/>
</form>
<p v-for="ps in searchfunc" :key="ps">{{ps.name}}</p>
</div>
</template>
<script>
export default {
name: "Home",
};
</script>
This error occurs when trying to use a property or method in the template (or render function) that doesn't exist on the component instance.
In this case it's because searchs and searchFunc variables used in the template of Home.vue are not found below on the instance. They are in the wrong file and need to be moved into Home.vue. Data needs to also go inside the data option:
main.js
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
Home.vue
<script>
const Hotels = [
{ name: "Sham", city: "Damascus", bed: 1, price: 100, id: "h1" },
{ name: "Shahbaa", city: "Aleppo", bed: 3, price: 200, id: "h2" },
{ name: "abcd", city: "Homs", bed: 5, price: 350, id: "h3" },
];
export default {
name: "Home",
data() {
return {
searchs: '',
Hotels,
}
},
computed: {
searchfunc() {
return this.Hotels.filter((srh) => {
return srh.price >= parseInt(this.searchs);
});
}
}
};
</script>

Using map on array of objects results in a errormessage

I am trying to figure out why this simple code does not work, it feels like I have done exactly the same thing many times before without errors. What have I done wrong?
import React, {useState} from 'react'
import { MenuItem } from '../menu-item/menu-item.component'
import './directory.styles.scss'
export const Directory = () => {
const sections = [
{
title: 'hats',
imageUrl: 'https://i.ibb.co/cvpntL1/hats.png',
id: 1,
linkUrl: 'shop/hats'
},
{
title: 'jackets',
imageUrl: 'https://i.ibb.co/px2tCc3/jackets.png',
id: 2,
linkUrl: 'shop/jackets'
},
{
title: 'sneakers',
imageUrl: 'https://i.ibb.co/0jqHpnp/sneakers.png',
id: 3,
linkUrl: 'shop/sneakers'
},
{
title: 'womens',
imageUrl: 'https://i.ibb.co/GCCdy8t/womens.png',
size: 'large',
id: 4,
linkUrl: 'shop/womens'
},
{
title: 'mens',
imageUrl: 'https://i.ibb.co/R70vBrQ/men.png',
size: 'large',
id: 5,
linkUrl: 'shop/mens'
}
];
return (
<div className="directory-menu">
{sections.map((title, imageUrl, id) => <MenuItem key={id} title={title} imageUrl={imageUrl}/>)}
</div>
)
}
Error Message:
Error: Objects are not valid as a React child (found: object with keys
{title, imageUrl, id, linkUrl}). If you meant to render a collection
of children, use an array instead.
You are not destructuring properly i.e.
.((title, imageUrl, id) =>
should be
.(({title, imageUrl, id}) =>
Check out this post, it's a common React error.
You could also try something like this
Object.entries(sections).map((x)=>
return x.title;
})

problem with infinite loop in function hook useEffect

I have a problem with an infinite loop on my hook,
I'm passing the data of the local JSON breakfast. If you are iterating with map the data and I am taking it to paint a menu of buttons.
If I remove the data at the end of the function, and leave the empty array, it sends me the following error:
const BreakfastComponent = () => {
const breakfast = [
{
id: 0,
name: "Sandwich de jamón y queso",
price: '35',
img: "https://i.ibb.co/ynC9xHZ/sandjc.png",
},
{
id: 1,
name: "Jugo Natural",
price: '15',
img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
},
{
id: 2,
name: "Café americano",
price: '20',
img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
},
{
id: 3,
name: "Café con leche",
price: '28',
img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
}
];
const [stateProduct, setStateProduct] = useState([ ]);
useEffect(() => {
setStateProduct(breakfast);
}, [breakfast]);
return (
<section className="databreakfast">
{stateProduct.map((element, item) =>
<ButtonsBComponent
key={item}
{...element}
/>
)}
</section>
)
};
export default BreakfastComponent;
React Hook useEffect has a missing dependency: 'breakfast'. Either include it or remove the dependency array react-hooks/exhaustive-deps
The problem is simple, you have breakfast array as a dependency to useEffect and in useEffect you are setting the breakfast array itself. Now since the const breakfast array is declared inside the component, a new reference to it is generated everytime and since useEffect sets the array in state, it re-renders and on next re-render the comparison for breakfast array fails since the reference has changed.
The solution is simple, you don't need to have the const array in the component and also you don't need to use useEffect
const breakfast = [
{
id: 0,
name: "Sandwich de jamón y queso",
price: '35',
img: "https://i.ibb.co/ynC9xHZ/sandjc.png",
},
{
id: 1,
name: "Jugo Natural",
price: '15',
img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
},
{
id: 2,
name: "Café americano",
price: '20',
img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
},
{
id: 3,
name: "Café con leche",
price: '28',
img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
}
];
const BreakfastComponent = () => {
const [stateProduct, setStateProduct] = useState(breakfast);
return (
<section className="databreakfast">
{stateProduct.map((element, item) =>
<ButtonsBComponent
key={item}
{...element}
/>
)}
</section>
)
};
export default BreakfastComponent;
useEffect's second argument is an array of state/hooks to be watched and when they change, to run the effect. Since your breakfast is a const, I'm guessing you just want the original stateProduct to be breakfast. So instead of using [] as the default, use breakfast.
const [stateProduct, setStateProduct] = useState(breakfast);
Also, probably a good idea to declare const breakfast ... outside of your react functional component so it doesn't re-declare it on every re-render.

Simply return a value from another component

Wondering if you guys can help. I am trying to create a generic component which when called, will return a value.
The code currently stands as follows:
import React, {Component} from 'react'
class Clients extends Component {
render () {
var userEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3,
properties: {
1: {name: "Admin", value: 1},
2: {name: "Manager", value: 2},
3: {name: "Standard", value: 3}
}
};
const clientName = (value) => {
return userEnum.properties[value].name
}
return null
}
}
export default Clients
and in another component, I try calling the clientName function (done an import too).
import ClientHelper from '../../helpers/clients'
...
const test = ClientHelper.clientName(2)
console.log(test)
I should expect a return value of 'Manager' but I get
TypeError: WEBPACK_IMPORTED_MODULE_9__helpers_clients.a.clientName
is not a function
You are declaring the function clientName inside the render method of the class Clients. This function is only accessible inside it's scope, the render method.
To access the function like you would, by calling the class Clients static method clientName, you should write it like this:
import React, { Component } from 'react'
class Clients extends Component {
static userEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3,
properties: {
1: { name: "Admin", value: 1 },
2: { name: "Manager", value: 2 },
3: { name: "Standard", value: 3 }
}
};
static clientName(value) {
return Clients.userEnum.properties[value].name;
}
render() {
return null;
}
}
export default Clients
If you do not intend to render anything with this class, you do not need react, and can simply create a utility/static class like below:
export default class Clients {
static userEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3,
properties: {
1: { name: "Admin", value: 1 },
2: { name: "Manager", value: 2 },
3: { name: "Standard", value: 3 }
}
};
static clientName(value) {
return Clients.userEnum.properties[value].name;
}
}
the function clientName is not a property of your class, but a local function inside the render function and therefore not accessible from the outside.
To solve this, you have to make clientName as well as your userEnum properties of the Clients object, for example in the constructor:
import React, {Component} from 'react'
class Clients extends Component {
constructor(props){
super(props);
this.userEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3,
properties: {
1: {name: "Admin", value: 1},
2: {name: "Manager", value: 2},
3: {name: "Standard", value: 3}
}
};
}
function clientName (value) {
return this.userEnum.properties[value].name
}
function render () {
return null
}
}
export default Clients

Categories

Resources