I tried to build a PWA with next.js
My idea is that i call the API to get data .But sometimes that API does not give the right datatypes or the data are not available.
My project is about showing the canteen nearby and show theirs menu
I checked the API , so i knew that sometime it give back the wrong data for the date.
Could someone to help me to handle it.
Here is my codes :
import {useState} from 'react';
import {useEffect} from 'react';
import {useRouter} from 'next/router';
console.log('test');
const Test = () => {
const current = new Date();
const year = current.getFullYear();
const month = current.getMonth() + 1;
const day = current.getDate();
const today = `${year}-${month<10?`0${month}`:`${month}`}-${day}`;
const [date, setDate] = useState(today);
const [menu, setMenu] = useState([]);
const router = useRouter();
const { id } = router.query;
console.log(id);
console.log(date);
const handleMenu = async () => {
const open = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}`);
const openData = await open.json();
console.log(openData);
console.log(openData['closed']);
if (openData['closed'] === false) {
const res = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}/meals`);
const data = await res.json();
console.log(data);
setMenu(data);
}
else {
console.log('closed');
const data = [{id:1,name :'Mensa ist geschlossen'}];
}
}
return (
<div>
<input type="text"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button onClick={handleMenu}>Get Menu</button>
<h1>Menu</h1>
<p>This is the Menu page</p>
{menu.map((meal) => (
<div key={meal.id}>
<h3>{meal.name}</h3>
<p>Price for students :{meal.prices.students}</p>
<p>Price for employees :{meal.prices.employees}</p>
<p>Price for othters :{meal.prices.others}</p>
<p>Price for pupils :{meal.prices.pupils} kostenlos</p>
</div>))}
</div>
);
}
export default Test;
And here is the error i got
Unhandled Runtime Error
pages/mensen/[id]/review/menu.js (26:40) # eval
24 | const open = await fetch(`https://openmensa.org/api/v2/canteens/${id}/days/${date}`);
25 |
> 26 | const openData = await open.json();
| ^
27 | console.log(openData);
28 | console.log(openData['closed']);
29 |
Thank you so much .
Related
Hi how can I use https://momentjs.com/docs/#/i18n/ in react native ? I exactly need to know how to change the language on my calendar.
Now I have name mounths in Polish but name days I have in english but I nedd Polish.
import momentPL from 'moment/src/locale/pl'
function TermeScreen({ route, navigation }) {
const { id, title } = route.params;
const [selectedDate, setSelectedDate] = useState(new Date());
moment.locale('pl',momentPL );
let startDate = moment()
Try this,
import moment from 'moment';
function TermeScreen({ route, navigation }) {
const { id, title } = route.params;
const [selectedDate, setSelectedDate] = useState(new Date());
let startDate = moment(selectedDate.format("YYYY-MM-DD");
}
I need a function for getting notification from socket (TypeScript) .
For instance ,
when a user click the "Like",the receiver will receive a notice like "You have receive a like from XXX",and I am able to get this message from the below code ,however ,I am not sure how to save those notifications into a list in order to display all the notices ..Could you please take a look how to do it ? Thank you so much in advance !!
I have putted the socket in the useContext :
import React from 'react';
import socketio from 'socket.io-client';
export const socket = socketio.connect(SOCKET_URL);
export const SocketContext = React.createContext();
When I send click a like, the receiver can receive my notification, and then the remark in the below codes,I can't get the notification list :
import {SocketContext} from '../../auth/context';
import React, {useEffect, useState, useContext, useLayoutEffect} from 'react';
const Home = () =>{
const {socket, user} = useContext(SocketContext);
const [notificationCount, setNotificationCount] = useState([]);
const [me, setMe] = useState({});
// init data
const initialData = async () => {
try {
const meResult = await fetchGetMe();
setMe(meResult?.data.data);
} catch (error) {
console.log('initial data get errors:', error);
}
};
useLayoutEffect(() => {
initialData();
}, []);
//get feedback from socket
useEffect(() => {
socket.on('getNotification', data => {
setNotificationCount(pre=> [...pre, data]); //I got the problem here..Can't get the list
console.log('notification data :', notificationCount);
});
return () => {
socket.off('getNotification');
};
}, [socket]);
const onPressLike = ()=>{
socket.emit('sendNotification', {
senderUserId: me?.userId,
senderName: me?.userName,
receiverUserId: 123456,
type: 0, // 0:like 1.gifts 2.sunflower
});
}
<Button onClick={onPressLike}>Like</Button>
}
3.My socket config in the server part :
let onlineUsers = [];
const addUsers = (userId, socketId) => {
!onlineUsers.some((m) => m.userId !== userId) &&
onlineUsers.push({ userId, socketId });
};
const removeUser = (socketId) => {
onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId);
};
const getUser = (receiverId) => {
return onlineUsers.find((m) => m.userId === receiverId);
};
io.on("connection", (socket) => {
console.log("connect now");
socket.on("newUser", (userId) => {
addUsers(userId, socket.id);
console.log("onlineUsers:", onlineUsers);
});
socket.on(
"sendNotification",
({ senderUserId, senderName, receiverUserId, type }) => {
console.log(
`senderName:${senderName},receiverID:${receiverUserId};type:${type},socketId:${socket.id};senderUserId:${senderUserId}`
);
console.log("sendNotification,onlineUsers:", onlineUsers);
let receiver = {};
if (onlineUsers.length > 0) {
receiver = getUser(senderUserId);
console.log("receiver:", receiver);
io.to(receiver.socketId).emit("getNotification", {
senderName,
type,
});
} else {
receiver = null;
console.log("receiver:", receiver);
socket.emit("getNotification", { receiver });
}
}
);
socket.on("disconnect", () => {
console.log("disconnect");
});
});
I'm currently trying to bring data from my MS SQL database into React components without causing a Promise error. Basically, this inherently involves async functions, but every time I use them, I get an error claiming that I'm trying to pass a Promise rather than an actual array into React.
How do I overcome this issue and pull data via prisma into Typescript and then transfer it into a React component without having complaints about a Promise?
Here's my code:
export const getServerSideProps = async () => {
const res = await fetch("http://localhost:8081/api/fRED_Market_Yield_10Y");
const my10y = await res.json();
return {
props: { my10y },
};
};
export function MY10Y({ my10y: [] }) {
return (
<div>
{my10y?.map((p: { DateTime: Key | null | undefined; Value: boolean | ReactChild | ReactFragment | ReactPortal | null | undefined; }) => {
return (
<div key={p.DateTime}>
<p>
{p.Value}%
</p>
</div>
);
})}
</div>
);
}
// pages/api/products.js
import { Prisma, PrismaClient } from "#prisma/client";
import { Key, ReactChild, ReactFragment, ReactPortal } from "react";
let prisma: PrismaClient<Prisma.PrismaClientOptions, never, Prisma.RejectOnNotFound | Prisma.RejectPerOperation | undefined>;
prisma = new PrismaClient();
//export default prisma;
export default async function handle(req: any, res: { json: (arg0: any) => void; }) {
const my10y = await prisma.fRED_Market_Yield_10Y.findMany();
res.json(my10y);
}
I am really struggling to find where I am going wrong with this. I am trying to move the picked (ImagePicker) image from cache to app scope directory folder named images/. I created a directory images/ using FileSystem.makeDirectoryAsync but while trying to move the picked image to this directory I am getting an error. Please can someone help me I am really struggling
Expected Result
The image successfully moves to the images/ directory
Actual Result
[Unhandled promise rejection: Error: File 'file:///var/mobile/Containers/Data/Application/318CFCE4-16DF-44DD-92B3-39DECA61EA14/Library/Caches/ExponentExperienceData/%2540user%252FtestApp/ImagePicker/ECD218AE-3DD3-429F-B1F5-469DA1AC661C.jpg' could not be moved to
'file:///var/mobile/Containers/Data/Application/318CFCE4-16DF-44DD-92B3-39DECA61EA14/Documents/ExponentExperienceData/%2540user%252FtestApp/images/ECD218AE-3DD3-429F-B1F5-469DA1AC661C.jpg/'.]
This is my code:
import React, { useEffect, useState } from "react";
import {Text,View,TouchableOpacity,Alert,} from "react-native";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";
import * as FileSystem from "expo-file-system";
const ImageCard = (props) => {
const { handlePickedImage } = props;
const [image, setImage] = useState("");
// Create any app folders that don't already exist
export const checkAndCreateFolder = async folder_path => {
const folder_info = await FileSystem.getInfoAsync(folder_path);
if (!Boolean(folder_info.exists)) {
// Create folder
console.log("checkAndCreateFolder: Making " + folder_path);
try {
await FileSystem.makeDirectoryAsync(folder_path, {
intermediates: true
});
} catch (error) {
// Report folder creation error, include the folder existence before and now
const new_folder_info = await FileSystem.getInfoAsync(folder_path);
const debug = `checkAndCreateFolder: ${
error.message
} old:${JSON.stringify(folder_info)} new:${JSON.stringify(
new_folder_info
)}`;
console.log(debug);
}
}
};
const veryfiyPermissons = async () => {
const result = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (result.status !== "granted") {
Alert.alert(
"Insufficient permissions",
"You need to grant permissions to access Camera Roll",
[{ text: "Okay" }]
);
return false;
}
return true;
};
const selectImageHandler = async () => {
const hasPermisson = await veryfiyPermissons();
if (!hasPermisson) {
return;
}
const image = await ImagePicker.launchImageLibraryAsync({
quality: 0.5,
});
if (image.cancelled) {
randomImage;
} else {
let localUri = image.uri;
let localUriNamePart = localUri.split("/");
const fileName = localUriNamePart[localUriNamePart.length - 1];
const images_folder = `${FileSystem.documentDirectory + 'images/'}`
checkAndCreateFolder(images_folder);
const setTheFile = `${images_folder + `${fileName}/`}`
await FileSystem.moveAsync({
from: localUri,
to: newLocation
}).then((i) => {
setImage(setTheFile);
handlePickedImage(setTheFile);
})
}
};
return (
<View>
<TouchableOpacity onPress={selectImageHandler}>
<Text>Add Photo</Text>
</TouchableOpacity>
</View>
);
};
export default ImageCard;
I am running the following test in a Vue app:
import axios from 'axios';
import flushPromises from 'flush-promises';
import MockAdapter from 'axios-mock-adapter';
import TenantAlertService from '#/services/TenantAlertService';
import ServiceUrlProvider from '#/utils/ServiceUrlProvider';
import userAlerts from '#/store/modules/userAlerts';
import AlertToPlain from '#/transform/AlertToPlain';
import Alert from '#/models/Alert';
describe('TenantAlertService Service', () => {
let mock;
let data;
const tenantCode = 'RedAlert';
const id = 'zyx-abc';
const personId = '123456';
const appCode = 'asdfklj3';
const message = {
text: 'foo',
template: 'MY_TEMPLATE',
};
const person = {
id: personId,
};
const messageUrl = ServiceUrlProvider.gmiUrl()
.concat('/tenant/')
.concat(tenantCode)
.concat('/person/')
.concat(id)
.concat('/message');
const responseUrl = ServiceUrlProvider.gmiUrl()
.concat('/tenant/')
.concat(tenantCode)
.concat('/person/')
.concat(id)
.concat('/message/response');
const sendMessageUrl = ServiceUrlProvider.gmiUrl()
.concat('/tenant/')
.concat(tenantCode)
.concat('/app/')
.concat(appCode)
.concat('/template/')
.concat(message.template)
.concat('/person/')
.concat(person)
.concat('/message');
beforeEach(() => {
mock = new MockAdapter(axios);
data = { response: true };
});
it('fetchAll should be called', async () => {
const messageData = [
'ele1',
];
const responseData = [
'ele2',
];
mock.onGet(messageUrl).reply(200, messageData);
mock.onGet(responseUrl).reply(200, responseData);
const resp = await TenantAlertService.fetchAll({ tenantCode, id });
expect(resp.data).toEqual(['ele1', 'ele2']);
});
it('sendMessage should be called', async () => {
mock.onPost(sendMessageUrl).reply(200, data);
const resp = await TenantAlertService.sendMessage({
tenantCode,
appCode,
personId,
message,
});
expect(resp.status).toBe(200);
});
/* Store Actions */
it('store sendMessage', async () => {
const context = {
dispatch: jest.fn(),
getters: {
getComponent: 'Component 1',
},
};
mock.onPost(sendMessageUrl).reply(200, new Alert({}));
userAlerts.actions.sendMessage(context, {
tenantCode,
appCode,
person,
message,
});
await flushPromises();
expect(context.dispatch).toHaveBeenCalledWith('addOneSorted', new AlertToPlain(new Alert({})));
});
});
and getting the following results on the last two tests(sendMessage should be called and store sendMessage):
Request failed with status code 404
at createErrorResponse (node_modules/axios-mock-adapter/src/utils.js:117:15)
at Object.settle (node_modules/axios-mock-adapter/src/utils.js:97:16)
at handleRequest (node_modules/axios-mock-adapter/src/handle_request.js:78:11)
at node_modules/axios-mock-adapter/src/index.js:18:9
at MockAdapter.<anonymous> (node_modules/axios-mock-adapter/src/index.js:17:14)
at dispatchRequest (node_modules/axios/lib/core/dispatchRequest.js:59:10)
I am running the exact same configuration for mocking axios calls in 19 other tests that are passing, so I'm fairly certain the issue is not with my axios config (as seen here for example).
Is there something else I'm missing that could be causing this error?