NextJs Server Side props not getting the data to pass to component - javascript

I got stuck with this problem and don't know how to fix it. I set up the server side props and it's working on the terminal on vscode but when i inspect in chrome or try to do something with it well, nothing appears.
export const getServerSideProps = async (context) => {
try {
let properties = []
const propertiesRef = collection(firestore, 'properties')
const q = query(propertiesRef, orderBy("propertiename", "desc"))
onSnapshot(q, (snapshot) => {
properties.push(snapshot.docs.map((doc) => (
{ ...doc.data(), id: doc.id }
)))
console.log(properties)
});
return {
props: {
propertiesProps : properties,
}
}
} catch(error) {
console.log(error)
}
}
When i pass the data here in the page i dont get anything back
function index({propertiesProps}) {
const [properties, setProperties] = useState([])
useEffect(async () => {
setProperties( propertiesProps)
console.log(properties)
}, [])
return (
<div>
<Head>
<title>Rimoz | Properties</title>
</Head>
<h1 className="main">Heres is the list of properties</h1>
<PropertieGallery />
<h1 className="main">Com server side props</h1>
<p></p>
</div>
)
}
export default index
And this is what i get in the terminal on vscode
[
[
{
propertiename: 'casa 57',
photos: [Array],
id: 'lKOfK8oirnLY5DNEJagH'
},
{
propertiename: 'casa 56',
photos: [Array],
id: 'r1IRpreknf5Pd7FqRUqJ'
},
{
photos: [Array],
propertiename: 'casa 55',
id: 'H2ADAlP4dyuZJCsYNnor'
},
{
propertiename: 'casa 54',
photos: [Array],
id: 'dB8wHXjwFHGB3JoIIGQv'
},
{
propertiename: 'casa 4 ',
photos: [Array],
id: 'jApsE2wgxBpdbajuObgx'
},
{
propertiename: 'casa 3 ',
photos: [Array],
id: 'mrOJasIuHUXI5ojISSWD'
},
{
photos: [Array],
propertiename: 'casa 2',
id: 'rBOG1mXUewKYiH47MbdM'
},
{
photos: [Array],
propertiename: 'casa 14',
id: 'c3ozTup7m1ZWIjSSzh7v'
}
]
]
What am i missing here?

Related

How to access "groups" using "class-transformer" in nested components

I'm trying to limit access to some properties to only users with that property on their group in a deeply nested interface, and I'm unable to access the "groups" metadata in the nested components.
Here is a code example:
Example of response:
export class ProductResponseInterface {
// groups work fine here
#ValidateNested()
success: boolean;
#Type(() => ProductFetchResponseInterface)
data?: ProductFetchResponseInterface;
error?: string;
#Exclude()
groups?: string[];
constructor(partial: Partial<ProductResponseInterface>) {
Object.assign(this, partial);
}
}
export class ProductFetchResponseInterface {
// groups seem to be undefined here
#ValidateNested()
#Type(() => ProductInterface)
#Expose({ groups: ['eshop.products'] })
products: ProductInterface[];
#Exclude()
groups: string[];
count: number;
constructor(partial: Partial<ProductFetchResponseInterface>) {
Object.assign(this, partial);
}
}
export class ProductInterface {
// groups seems to be undefined here
#Expose({ groups: ['eshop.products.product.id', 'admin'] })
id: number;
#Expose({ groups: ['eshop.products.product.name'] })
name: string;
...
constructor(partial: Partial<ProductInterface>) {
Object.assign(this, partial);
}
}
The problem:
ProductFetchResponseInterface and ProductInterface don't have access to the "groups" tag, and their response returns empty products.
This is the call that uses those interfaces
const http_response = await this.handle_request(url);
// { success: true, data: { products: [ { id: 1, name: 'product_name' }]}}
return plainToInstance(
ProductResponseInterface,
{
...response,
groups: user.access_permissions_populated // ['eshop.products', 'eshop.products.product.id',...],
},
{},
);
Any idea on how to make it work?
Thanks.
You need call plainToInsatnce like this
plainToInstance(ProductResponseInterface, plainObject, { groups: ["eshop.products", "eshop.products.product.name", "eshop.products.product.id"] })
There is test example
import "reflect-metadata";
import { plainToInstance } from "class-transformer"
import { ProductResponseInterface } from "./test"
describe("", () => {
it("tranform items by groups attribute", () => {
const raw = { success: true, data: { products: [{ id: 1, name: 'product_name' }] } }
const res = plainToInstance(ProductResponseInterface, raw, { groups: ["eshop.products", "eshop.products.product.name", "eshop.products.product.id"] })
const exp: ProductResponseInterface = {
success: true,
data: {
products: [
{
id: 1,
name: "product_name"
}
],
groups: undefined,
count: undefined,
}
}
expect(res).toEqual(exp);
});
});

Javascript nested map function return string

I have a set of data. I map through my data, if data is "HOME_DELIVERY then it will go to another function which will check is the order is valid or not. if the order is valid then it will return hello string. So far everything works as expected but I want my map function return string hello. currently it's returning ['hello']
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
retrun
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.map((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName);
Array.map returns an array as response. If you need a string as response, you have to modify the logic as
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
return;
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ef",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.flatMap((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName.join(''));
You can use filter before calling map
//if it has more than 1 items in the list, it will join them together like this `hellohellohello`
const orderIds = orders.filter((order) => order.deliveryMethod === 'HOME_DELIVERY').map(order => getRoundName(order.id)).join("")

Converting an array to an object of nested objects for a tree diagram in Javascript

i'm attempting to create a Tree Diagram with react-d3-js. It needs to be in a specific format. So i need to convert the initial data that i have to the format.
This is a diagram for a shop to see the distribution chain and who is allowed to make a purchase from specific nodes.
Initial Data:
store.name = 'Absolut Chocolat' //Main Parent
store.shopconditions: [
{
"role": "agent",
"condition": ["owner", "stokist"]
},
{
"role": "stokist",
"condition": ["owner", "master stokist"]
},
{
"role": "master stokist",
"condition": ["owner"]
}
]
// If role is agent, then they are allowed to buy from 'owner' and 'stokist'
Here's the hardcoded ideal output:
orgChart = {
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
],
},
],
};
With a few for each loops, i've gotten to the first 2 layers of the intended output but i cannot find a way to get more than that.
Here is what i got so far:
Agent node is not under Master Stokist
Current code:
let chartData = { name: store.name, children: [] };
store.shopconditions.forEach((i) => {
i.condition.forEach((c) => {
if (c === 'owner') {
chartData.children.push({ name: i.role });
}
});
});
const chartDataParser = (data) => {
data.children.map((i) => {
for (const [k, v] of Object.entries(i)) {
store.shopconditions.forEach((c) => {
c.condition.forEach((o) => {
if (o === v) {
if (!i.children) {
i.children = [{ name: c.role }];
} else {
i.children.push({ name: c.role });
}
}
});
});
}
});
};
chartDataParser(chartData);
Current output:
{
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
// Missing children: Agent Node
},
],
},
],
};
What the tree diagram should look like:
As you can see under Master Stokist node, Agent is under Stokist
The Agent node is not reached under the stokist node in the right most chain. I need a fix to my current code so it can go to that extra layer. Thanks in advance. Looking forward to learn from your answers.
You can build an object that lists children by role and then use that to recursively build the nodes of the object. Possibly something like the following:
const store = {
name: 'Absolut Chocolat',
shopconditions: [
{ "role": "agent", "condition": ["owner", "stokist"], name: 'Agent' },
{ "role": "stokist", "condition": ["owner", "master stokist"], name: 'Stockist' },
{ "role": "master stokist", "condition": ["owner"], name: 'Master Stockist' },
]
};
const build_role_map = (store) => {
let role_map = Object.fromEntries(
store.shopconditions.map((v) => [v.role, { ...v, children: [] }])
);
role_map.owner = { "role": "owner", "condition": [], children: [], name: store.name };
store.shopconditions.forEach(
({ role, condition }) => {
condition.forEach((parent) => { role_map[parent].children.push(role) })
}
);
return role_map;
};
const build_node = (role_map, { name, children }) => {
let node = { name };
if(children.length > 0)
node.children = children.map((child) => build_node(role_map, role_map[child]));
return node;
};
const build_tree = (store) => {
const role_map = build_role_map(store);
return build_node(role_map, role_map.owner);
};
console.log(build_tree(store));

TypeError: Cannot read property 'message' of undefined

I'm not sure why I'm getting this error. I'm copying the code directly as is from "Pure React" by Dave Ceddia. I'm working on the github-file-list project.
const FileListItem = ({ file }) => (
<tr className="file-list-item">
<FileName file={file} />
<CommitMessage
commit={file.lastestCommit} />
</tr>
);
FileListItem.propTypes = {
file: PropTypes.object.isRequired
};
const CommitMessage = ({ commit }) => (
<td className="commit-message">
{commit.message}
</td>
);
CommitMessage.propTypes = {
commit: PropTypes.object.isRequired
};
const testFiles = [
{
id: 1,
name: 'src',
type: 'folder',
updated_at: '2016-07-11 21:24:00',
latestCommit: {
message: 'Initial commit'
}
},
{
id: 2,
name: 'tests',
type: 'folder',
updated_at: "2016-07-11 21:24:00",
latestCommit: {
message: 'Initial commit'
}
}, {
id: 3,
name: 'README',
type: 'file',
updated_at: "2016-07-18 21:24:00",
latestCommit: {
message: 'Added a readme'
}
},
];
The error points to where I to the CommitMessage component where I declare {commit.message}.
Probably has something to do with this
const FileListItem = ({ file }) => (
<tr className="file-list-item">
<FileName file={file} />
<CommitMessage
commit={file.lastestCommit} />
</tr>
);
lastestCommit, looks like a typo.

vue.js push array component

1.vue.js problem component
i want insert a new message in new array with method on click event but
not work for me because function is incomplete
where is the problem.
help me please.
<div class="col-lg-12">
<h1>{{message.title}}</h1>
<h4>{{message.subtitle}}</h4>
</p> {{message.body}}</p>
<button v-on:click="newMessage">Reverse Message</button>
</div>
import {
VueTabs,
VTab
}
from "vue-nav-tabs";
import "vue-nav-tabs/themes/vue-tabs.css";
export default {
components: {
VueTabs,
VTab
},
data() {
return {
title: "elenco",
messages: [{
id: 1,
title: "titolo",
subtitle: "sottotitolo",
body: "argomento",
author: "Amedeo",
date: "17/07/2017",
files: [{
id: 1,
title: "Allegatoriunione",
openfile: "Allegato.pdf"
}, ],
methods: {
newMessage: function() {
this.message.title = this.message.title
.push("")
.split("")
.reverse()
.join("");
}
Your Code Contains many syntax errors which probably fails silently.
Try this new updated code:
<script>
import { VueTabs, VTab } from 'vue-nav-tabs'
import 'vue-nav-tabs/themes/vue-tabs.css'
export default {
components: { VueTabs, VTab },
data() {
return {
title: 'elenco',
messages: [
{
id: 1,
title: 'titolo',
subtitle: 'sottotitolo',
body: 'argomento',
author: 'Amedeo',
date: '17/07/2017',
files: [
{
id: 1,
title: 'Allegatoriunione',
openfile: 'Allegato.pdf'
}
]
}
]
}
},
methods: {
newMessage() {
this.message.title = this.message.title
.push('')
.split('')
.reverse()
.join('')
}
}
}
</script>

Categories

Resources