use createVNode for antdvue component cannot resolve? - vuejs3

i use antd vue model to create a confirm modal,and use createVNode for my content
const modalRef = Modal.confirm({
content: createVNode(CategoryTreeAddModal),
centered: true,
icon: undefined,
onCancel: (event) => {
console.log(CategoryTreeAddModal)
// modalRef.destroy();
},
onOk: (event) => {
console.log(CategoryTreeAddModal)
// modalRef.destroy();
}
})
and this is my content code
<template>
<a-form ref="formRef" :model="formState" :rules="rules" class="login-form">
<a-form-item ref="name" name="name">
<a-input v-model:value="formState.name" placeholder="请输入名称" />
</a-form-item>
</a-form>
</template>
it just warning me Failed to resolve component:a-input a-form-item a-form, how to resolve,ijust wanna use this way to create my confirm modal

You can try this
const instalce = getCurrentInstance()
const vnode = createVNode(CategoryTreeAddModal)
vnode.appContext = instance.appContext
const modalRef = Modal.confirm({
content: vnode,
centered: true,
icon: undefined,
onCancel: (event) => {
console.log(CategoryTreeAddModal)
// modalRef.destroy();
},
onOk: (event) => {
console.log(CategoryTreeAddModal)
// modalRef.destroy();
}
})

Related

MUI snackbar div persist on DOM after being closed

I created a global modal with the purpose of only calling it when I need it, but the problem is that the snackbar div persists in the DOM and this causes certain elements to be blocked because they are below this div. Any idea what the problem would be?
My GlobalAlert component:
export function GlobalAlert() {
const {alertState, handleClose} = useAlertContext();
const {open, type, message} = alertState;
function TransitionDown(props: TransitionProps) {
return <Slide {...props} direction="down" />;
}
return (
<Snackbar
key={"top" + "center"}
TransitionComponent={TransitionDown}
anchorOrigin={{vertical: "top", horizontal: "center"}}
autoHideDuration={4000}
disableWindowBlurListener={true}
open={open}
onClose={handleClose}
>
<Alert severity={type} sx={useStyles.alert} variant="filled" onClose={handleClose}>
{message}
</Alert>
</Snackbar>
);
}
Context where I get the info
const AlertContextProvider = (props: any) => {
const [alertState, setAlertState] = React.useState<AlertState>({
open: false,
type: "error",
message: "",
});
const handleClose = React.useCallback((event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === "clickaway") {
return;
}
setAlertState({
open: false,
type: "error",
message: "",
});
}, []);
const value = React.useMemo(
() => ({
alertState,
setAlertState,
handleClose,
}),
[alertState, handleClose],
);
return <AlertContext.Provider value={value} {...props} />;
};
Bug image

How to properly implement toast-ui/calendar in nextjs

I am trying to implement #toast-ui/react-calendar, initially I was getting window is not defined but after implementing the fix I got here https://github.com/nhn/toast-ui.react-calendar/issues/39, I got this instead Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of __WEBPACK_DEFAULT_EXPORT__.
This is my curent code
CalendarPage.js
import React from 'react';
import Calendar from '#toast-ui/react-calendar';
import 'tui-calendar/dist/tui-calendar.css';
import 'tui-date-picker/dist/tui-date-picker.css';
import 'tui-time-picker/dist/tui-time-picker.css';
export default (props) => <Calendar {...props} ref={props.forwardedRef} />;
schedule>index.jsx
import { forwardRef, useCallback, useRef, useState } from 'react';
import dynamic from 'next/dynamic';
const TuiCalendar = dynamic(() => import('#components/calendars/CalendarPage'), { ssr: false });
const CalendarWithForwardedRef = forwardRef((props, ref) => (
<TuiCalendar {...props} forwardedRef={ref} />
));
const start = new Date();
const end = new Date(new Date().setMinutes(start.getMinutes() + 30));
const schedules = [
{
calendarId: '1',
category: 'time',
isVisible: true,
title: 'Study',
id: '1',
body: 'Test',
start,
end,
},
{
calendarId: '2',
category: 'time',
isVisible: true,
title: 'Meeting',
id: '2',
body: 'Description',
start: new Date(new Date().setHours(start.getHours() + 1)),
end: new Date(new Date().setHours(start.getHours() + 2)),
},
];
const calendars = [
{
id: '1',
name: 'My Calendar',
color: '#ffffff',
bgColor: '#9e5fff',
dragBgColor: '#9e5fff',
borderColor: '#9e5fff',
},
{
id: '2',
name: 'Company',
color: '#ffffff',
bgColor: '#00a9ff',
dragBgColor: '#00a9ff',
borderColor: '#00a9ff',
},
];
const SchedulePage = () => {
const cal = useRef(null);
const onClickSchedule = useCallback((e) => {
const { calendarId, id } = e.schedule;
const el = cal.current.calendarInst.getElement(id, calendarId);
console.log(e, el.getBoundingClientRect());
}, []);
const onBeforeCreateSchedule = useCallback((scheduleData) => {
console.log(scheduleData);
const schedule = {
id: String(Math.random()),
title: scheduleData.title,
isAllDay: scheduleData.isAllDay,
start: scheduleData.start,
end: scheduleData.end,
category: scheduleData.isAllDay ? 'allday' : 'time',
dueDateClass: '',
location: scheduleData.location,
raw: {
class: scheduleData.raw['class'],
},
state: scheduleData.state,
};
cal.current.calendarInst.createSchedules([schedule]);
}, []);
const onBeforeDeleteSchedule = useCallback((res) => {
console.log(res);
const { id, calendarId } = res.schedule;
cal.current.calendarInst.deleteSchedule(id, calendarId);
}, []);
const onBeforeUpdateSchedule = useCallback((e) => {
console.log(e);
const { schedule, changes } = e;
cal.current.calendarInst.updateSchedule(schedule.id, schedule.calendarId, changes);
}, []);
function _getFormattedTime(time) {
const date = new Date(time);
const h = date.getHours();
const m = date.getMinutes();
return `${h}:${m}`;
}
function _getTimeTemplate(schedule, isAllDay) {
var html = [];
if (!isAllDay) {
html.push('<strong>' + _getFormattedTime(schedule.start) + '</strong> ');
}
if (schedule.isPrivate) {
html.push('<span class="calendar-font-icon ic-lock-b"></span>');
html.push(' Private');
} else {
if (schedule.isReadOnly) {
html.push('<span class="calendar-font-icon ic-readonly-b"></span>');
} else if (schedule.recurrenceRule) {
html.push('<span class="calendar-font-icon ic-repeat-b"></span>');
} else if (schedule.attendees.length) {
html.push('<span class="calendar-font-icon ic-user-b"></span>');
} else if (schedule.location) {
html.push('<span class="calendar-font-icon ic-location-b"></span>');
}
html.push(' ' + schedule.title);
}
return html.join('');
}
const templates = {
time: function (schedule) {
console.log(schedule);
return _getTimeTemplate(schedule, false);
},
};
return (
<div className='App'>
<h1>Welcome to TOAST Ui Calendar</h1>
<CalendarWithForwardedRef
ref={cal}
height='1000px'
useCreationPopup={true}
useDetailPopup={true}
calendars={calendars}
schedules={schedules}
onClickSchedule={onClickSchedule}
onBeforeCreateSchedule={onBeforeCreateSchedule}
onBeforeDeleteSchedule={onBeforeDeleteSchedule}
onBeforeUpdateSchedule={onBeforeUpdateSchedule}></CalendarWithForwardedRef>
</div>
);
};
export default SchedulePage;
I do not what I am doing wrong here but I keep getting this error
Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `__WEBPACK_DEFAULT_EXPORT__`.
Call Stack
createFiberFromTypeAndProps
node_modules\react-dom\cjs\react-dom.development.js (25058:0)
createFiberFromElement
node_modules\react-dom\cjs\react-dom.development.js (25086:0)
reconcileSingleElement
node_modules\react-dom\cjs\react-dom.development.js (14052:0)
reconcileChildFibers
node_modules\react-dom\cjs\react-dom.development.js (14112:0)
Turns out that the issue with my code was caused by clashing npm packages, I had react-big-calendar installed previously removing that fixed the issue

TypeError: dispatch is not a function when clicking the toggle button

I am using react redux-thunk. I have a set of users data that I get from an API and this is the schema:
.
I've connected the "active" property with the checked attribute of a Switch MUI button, so naturally when calling the API I have some users with their switch button already on "true". What I am trying to do is to just make the switch functional, and just be able to click it and change its state, not necessarily doing anything with that.
Here's my toggleType.js:
export const TOGGLE = "TOGGLE";
Here's my toggleAction.js:
import { TOGGLE } from "./toggleType";
const statusToggleAction = () => {
return {
type: TOGGLE,
};
};
export const statusToggle = () => {
return (dispatch) => {
dispatch(statusToggleAction);
};
};
Here's my toggleReducer.js:
import { TOGGLE } from "./toggleType";
const initialState = {
status: false,
};
const toggleReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE:
status: true;
default:
return state;
}
};
export default toggleReducer;
Everything is under my userContainer.js, like that:
function UserContainer({ userData, fetchUsers }) {
useEffect(() => {
fetchUsers();
}, []);
return userData.loading ? (
<h2>Loading</h2>
) : userData.error ? (
<h2>{userData.error}</h2>
) : (
<Container maxWidth="lg" style={{ flexGrow: 1, height: "100%" }}>
<h2>User List</h2>
<div>
{userData &&
userData.users &&
userData.users.map((user) => (
<div key={user.id}>
<p>{user.name}</p>
<Switch checked={user.active} onChange={statusToggle()} />
</div>
))}
</div>
</Container>
);
}
const mapStateToProps = (state) => {
return { userData: state.user, statusToggle: state.status };
};
const mapDispatchToProps = (dispatch) => {
return {
fetchUsers: () => dispatch(fetchUsers()),
statusToggle: () => dispatch(statusToggle()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserContainer);
This is the error I am getting whenever I am clicking one of those switches:
Any ideas are welcome, I "learned" redux like 3 days ago!
toggleReducer function in toggleReducer.js, replace status: true; with return { status: true }.
Just return action in statusToggle function in toggleAction.js without dispatch as following.
export const statusToggle = () => {
return statusToggleAction();
};
Or just call statusToggleAction directly in userContainer.js as following.
export const statusToggle = () => {
return (dispatch) => {
dispatch(statusToggleAction());
};
};

How can I override the client's state with the server's state in vue3 ssr?

When I was building vue3ssr recently, everything went smoothly, but the store data on the server side could never cover the store data on the client side. The following is my code, please help me to see where there is a problem
// entry-client.js
if (window && window.__INITIAL_STATE__) {
store.replaceState(window.__INITIAL_STATE__);
}
router.isReady().then(() => {
app.mount('#app')
})
<script>
<template>
<div class="home">
<h1>This is Home</h1>
<h2>ssr msg: {{ msg }}</h2>
</div>
</template>
<script setup>
import useStore from "#/store";
import { computed } from "vue";
const store = useStore();
const msg = computed(() => { // => msg: ''
return store.state.msg;
});
// console.log("store", store);
</script>
<script>
// views/home.vue
export default {
asyncData: (store) => {
return store.dispatch("asyncSetMsg");
},
};
</script>
</script>
// store/index.ts
export default function useStore() {
return createStore({
state: {
msg: "",
},
getters: {},
mutations: {
SET_MSG(state, payload) {
state.msg = payload;
},
},
actions: {
// store/index.ts
asyncSetMsg({ commit }) {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
commit("SET_MSG", "This is some msg in ssr");
resolve();
}, 300);
});
},
},
modules: {},
});
}
// entry-server.js
Promise.all(componentArr).then(() => {
console.log('store.state', store.state); // => {msg: 'This is some msg in ssr'}
html += `<script>window.__INITIAL_STATE__ = ${replaceHtmlTag(JSON.stringify(store.state))}</script>`
resolve(html);
}).catch(() => {
reject(html)
})
The above is the relevant code The following is the running result, I tried to print on the server side and the client side, the result is the normal output on the server side, but there is no data on the client sid

How to call a function from another component

I am using Alan AI voice assistant, so I am trying to trigger a function from another component based on the voice command.
This is the component holding the function I want to call
const CartButton: React.FC<CartButtonProps> = ({
className,
isShowing,
}) => {
const { openDrawer, setDrawerView } = useUI();
function handleCartOpen() {
setDrawerView('CART_SIDEBAR');
isShowing;
return openDrawer();
}
return (
<button
className={cn(
'flex items-center justify-center',
className
)}
onClick={handleCartOpen}
aria-label="cart-button"
>
</button>
);
};
export default CartButton;
So in the component above I want to use the handleCartOpen function in the below component
const COMMANDS = {
OPEN_CART: "open-cart",
}
export default function useAlan() {
const [alanInstance, setAlanInstance] = useState()
const openCart = useCallback(() => {
alanInstance.playText("Opening cart")
// I want to call the handleCartOpen function here
}, [alanInstance])
useEffect(() => {
window.addEventListener(COMMANDS.OPEN_CART, openCart)
return () => {
window.removeEventListener(COMMANDS.OPEN_CART, openCart)
}
}, [openCart])
useEffect(() => {
if (alanInstance != null) return
const alanBtn = require('#alan-ai/alan-sdk-web');
setAlanInstance(
alanBtn({
key: process.env.NEXT_PUBLIC_ALAN_KEY,
rootEl: document.getElementById("alan-btn"),
onCommand: ({ command, payload }) => {
window.dispatchEvent(new CustomEvent(command, { detail: payload }))
}
}));
}, []);
}
So in the openCart Callback, i want to trigger the handleCartOpen function which is in the first component

Resources