Test case in react of otpinput - onchange

import React, { memo, useState, useCallback, CSSProperties } from "react";
import SingleInput from "./SingleInput";
export interface OTPInputProps {
length: number;
onChangeOTP: (otp: string) => any;
autoFocus?: boolean;
isNumberInput?: boolean;
disabled?: boolean;
style?: CSSProperties;
className?: string;
inputStyle?: CSSProperties;
inputClassName?: string;
}
export function OTPInputComponent(props: OTPInputProps) {
const {
length,
isNumberInput,
autoFocus,
disabled,
onChangeOTP,
inputClassName,
inputStyle,
...rest
} = props;
const [activeInput, setActiveInput] = useState(0);
const [otpValues, setOTPValues] = useState(Array<string>(length).fill(""));
// Helper to return OTP from inputs
const handleOtpChange = useCallback(
(otp: string[]) => {
const otpValue = otp.join("");
onChangeOTP(otpValue);
},
[onChangeOTP]
);
// Helper to return value with the right type: 'text' or 'number'
const getRightValue = useCallback(
(str: string) => {
let changedValue = str;
if (!isNumberInput) {
return changedValue;
}
return !changedValue || /\d/.test(changedValue) ? changedValue : "";
},
[isNumberInput]
);
// Change OTP value at focussing input
const changeCodeAtFocus = useCallback(
(str: string) => {
const updatedOTPValues = [...otpValues];
updatedOTPValues[activeInput] = str[0] || "";
setOTPValues(updatedOTPValues);
handleOtpChange(updatedOTPValues);
},
[activeInput, handleOtpChange, otpValues]
);
// Focus `inputIndex` input
const focusInput = useCallback(
(inputIndex: number) => {
const selectedIndex = Math.max(Math.min(length - 1, inputIndex), 0);
setActiveInput(selectedIndex);
},
[length]
);
const focusPrevInput = useCallback(() => {
focusInput(activeInput - 1);
}, [activeInput, focusInput]);
const focusNextInput = useCallback(() => {
focusInput(activeInput + 1);
}, [activeInput, focusInput]);
// Handle onFocus input
const handleOnFocus = useCallback(
(index: number) => () => {
focusInput(index);
},
[focusInput]
);
// Handle onChange value for each input
const handleOnChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const val = getRightValue(e.currentTarget.value);
if (!val) {
e.preventDefault();
return;
}
changeCodeAtFocus(val);
focusNextInput();
},
[changeCodeAtFocus, focusNextInput, getRightValue]
);
// Hanlde onBlur input
const onBlur = useCallback(() => {
setActiveInput(-1);
}, []);
// Handle onKeyDown input
const handleOnKeyDown = useCallback(`how to write test case for this handleOnKeyDown`
(e: React.KeyboardEvent<HTMLInputElement>) => {`keyboardevent
`
switch (e.key) {
case "Backspace":
case "Delete": {
e.preventDefault();
if (otpValues[activeInput]) {
changeCodeAtFocus("");
} else {
focusPrevInput();
}
break;
}
case "ArrowLeft": {
e.preventDefault();
focusPrevInput();
break;
}
case "ArrowRight": {
e.preventDefault();
focusNextInput();
break;
}
case " ": {
e.preventDefault();
break;
}
default:
break;
}
},
[activeInput, changeCodeAtFocus, focusNextInput, focusPrevInput, otpValues]
);
const handleOnPaste = useCallback(
(e: React.ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
const pastedData = e.clipboardData
.getData("text/plain")
.trim()
.slice(0, length - activeInput)
.split("");
if (pastedData) {
let nextFocusIndex = 0;
const updatedOTPValues = [...otpValues];
updatedOTPValues.forEach((val, index) => {
if (index >= activeInput) {
const changedValue = getRightValue(pastedData.shift() || val);
if (changedValue) {
updatedOTPValues[index] = changedValue;
nextFocusIndex = index;
}
}
});
setOTPValues(updatedOTPValues);
setActiveInput(Math.min(nextFocusIndex + 1, length - 1));
}
},
[activeInput, getRightValue, length, otpValues]
);
return (
<div {...rest} data-testid="otp-test">
{Array(length)
.fill("")
.map((_, index) => (
<SingleInput
key={`SingleInput-${index}`}
focus={activeInput === index}
value={otpValues && otpValues[index]}
autoFocus={autoFocus}
onFocus={handleOnFocus(index)}
onChange={handleOnChange}
onKeyDown={handleOnKeyDown}
onBlur={onBlur}
onPaste={handleOnPaste}
style={inputStyle}
className={inputClassName}
disabled={disabled}
/>
))}
</div>
);
}
const OTPInput = memo(OTPInputComponent);
export default OTPInput;`how to write test case for this component`

Related

Multiple useEffect in react-native to achieve mentioned functionality

I need help with the async nature of Async storage and axios api. Here's the functionality that I am trying to achieve ->
send request to two separate api to get some data.
display that data on the screen with some additional text
api request are authenticated so a token is passed as Authentication Header
I have attached the current implementation, I am having the a number of errors in this
Errors:
Login_token not set in state after fetching from Async Storage.
Data not set in state after api call
both resulting in either failed api calls or undefined state errors on render
This is my code.
import React, { FunctionComponent, useEffect, useCallback, useState} from 'react';
import { StyleSheet, View} from 'react-native';
// chat
import { GiftedChat } from 'react-native-gifted-chat';
// navigation
import { RootStackParamList } from '../../navigators/RootStack';
import { StackScreenProps } from '#react-navigation/stack';
export type Props = StackScreenProps<RootStackParamList, "Chat">;
// api
import { Convo_details, Send_Msg, List_Msg, Expert_Public_Profile } from '../../api/UserApi';
import Spinner from 'react-native-loading-spinner-overlay';
import AsyncStorage from '#react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
const Chat: FunctionComponent<Props> = ({ navigation, route, ...props }) => {
// console.log(props.route.params);
const [login_token, setlogin_token] = useState('')
const [conversation_id, setconversation_id] = useState('')
const [conversation_details, setconversation_details] = useState({})
const [currentuser, setcurrentuser] = useState({})
const [loading, setLoading] = useState(false);
const [expertuid, setexpertuid] = useState('')
const [ExpertProfile, setExpertProfile] = useState({})
const [messages, setMessages] = useState([]);
useEffect(() => {
getlogintoken()
console.log("####################################","getlogintoken");
}, [])
/* conversationid */
useEffect(() => {
if (route.params != null) {
setconversation_id(route.params[0])
}
console.log("####################################","conversation id");
}, [])
/* expert uid */
useEffect(() => {
if (route.params != null) {
setexpertuid(route.params[1])
}
console.log("####################################","expert uid");
}, [])
/* expert public profile */
useEffect(() => {
getexpertpublicprofile()
getConvo_details()
console.log("####################################","convo_details");
}, [])
useEffect(() => {
// get current user
AsyncStorage.getItem("currentuser").then(res => {
if (res != null) setcurrentuser(res)
else alert("Current user not found")
})
console.log("####################################","current user");
}, [])
// set welcome msg
useEffect(() => {
if (Object.keys(conversation_details).length != 0 && Object.keys(ExpertProfile).length != 0)
setwelcomemsg()
}, [])
const onSend = useCallback(async (messages = []) => {
// console.log(messages[0].text);
setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
const data = {
conversation_id: "f98d6851-a713-4f58-9118-77a779ff175f",//conversation_id,
message_type: "TEXT",
body: messages[0].text
}
const res: any = await Send_Msg(data, login_token)
.catch(error => {
alert(`Send_Msg -> ${error}`)
console.log(error);
return
})
if (res.status == 200) {
console.log(res.data);
} else console.log(res);
}, [])
const getexpertpublicprofile = async () => {
setLoading(true)
const res: any = await Expert_Public_Profile(expertuid, login_token)
.catch(error => {
setLoading(false)
console.log("Expert public profile ->");
alert(`Expert public profile ->${error.message}`)
console.log(error);
return
})
setLoading(false)
if (res.status === 200) setExpertProfile(res.data)
else {
alert(`get expert public profile${res.data.message}`)
console.log("getexpertpublicprofile -->");
console.log(res.data);
}
}
const getlogintoken = () => {
AsyncStorage.getItem("login_token").then(res => {
if (res != null) {
setLoading(false)
setlogin_token(res)
}
else alert("No login token found")
})
}
const getConvo_details = async () => {
setLoading(true)
const res: any = await Convo_details(conversation_id, login_token)
.catch(error => {
setLoading(false)
alert(`Convo_details-->${error.message}`)
console.log("Convo_details -->");
console.log(error);
return
})
setLoading(false)
if (res.status === 200) setconversation_details(res.data)
else {
alert(`get convo details-> ${res.data.message}`)
console.log("getConvo_details -->");
console.log(res.data);
}
}
const setwelcomemsg = () => {
try {
let user = JSON.parse(currentuser)
let messages = [
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `About Me - ${ExpertProfile.bio}`,
user: {
_id: conversation_details.recipient.user_uid,
}
},
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `My name is ${conversation_details.recipient.name}`,
user: {
_id: conversation_details.recipient.user_uid,
}
},
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `Hi ${user.full_name}`,
user: {
_id: conversation_details.recipient.user_uid,
}
}]
setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
} catch (error) {
console.log("try -> set welcome msg");
console.log(error);
return
}
}
return (
<View style={styles.maincontainer}>
<Spinner
visible={loading}
textContent={'Loading...'}
textStyle={{ color: '#FFF' }}
/>
<GiftedChat
messages={messages}
onSend={messages => onSend(messages)}
user={{
_id: currentuser.user_uid,
}}
isTyping={false}
scrollToBottom={true}
showAvatarForEveryMessage={true}
renderAvatar={() => null}
/>
</View>
);
}
export default Chat;
const styles = StyleSheet.create({
maincontainer: {
flex: 1,
},
});
When axios returns, it usually give the response as res.data, so in your case, try either res.data or res.data.yourToken (I'm not sure how it's your object).
Gurav,
As far as your code above, The api call's will trigger even before you get currentuser or loginToken. You have to handle the api call after getting the currentuser and loginToken. This can be gracefully handled with async, await.
example code:
useEffect(() => {
getData()
}, [])
useEffect(() => {
if(login_token && currentuser) {
//The api call goes here after you get the logintoken andcurrentuser.
// The above condition is just an example but will vary based on your requirements
}
}, [login_token, currentuser])
const getData = async () => {
await getlogintoken()
await getcurrentuser()
}
const getlogintoken = async () => {
await AsyncStorage.getItem("login_token").then(res => {
if (res != null) {
setLoading(false)
setlogin_token(res)
}
else alert("No login token found")
})
}
const getcurrentuser = async () => {
await AsyncStorage.getItem("currentuser").then(res => {
if (res != null) setcurrentuser(res)
else alert("Current user not found")
})
}

how to reset navigation addListener when a state is changed

I want to reset navigation addListener when state is changed but It's not working
useEffect(() => {
const {page, pageIdx, tab} = pageInfo
const remove = navigation.addListener('state', ({data:{state:{routes, index}}}) => {
if(routes[index].name === name){
if(pageIdx)
getMatchItem(`usr/goods/match/buy/history/${tab}/${page}`)
else
getItem(`usr/goods/auction/bid/${tab}/${page}`)
}
return () => remove()
})
}, [pageInfo])
so I tried to return remove function when state is changed but It couldn't work
For example:
const [stateChanged, setStateChaged] = useState(false)
const [listener, setListener] = useState(null)
useEffect(() => {
if(stateChanged && listener) {
listener()
setListener(null)
}
}, [stateChanged])
useEffect(() => {
const {page, pageIdx, tab} = pageInfo
const remove = navigation.addListener('state', ({data: {state: {routes, index}}}) => {
if (routes[index].name === name) {
if (pageIdx)
getMatchItem(`usr/goods/match/buy/history/${tab}/${page}`)
else
getItem(`usr/goods/auction/bid/${tab}/${page}`)
setStateChaged(true)
}
})
setListener(remove)
}, [pageInfo])

EXPO-AV not playing sound and not throwing any errors

I am trying to load the sound which i retrieve from my own API into the EXPO AV createAsync function:
const PlayerWidget: React.FC = () => {
const [song, setSong] = useState(null);
const [sound, setSound] = useState<Sound | null>(null);
const [isPlaying, setIsPlaying] = useState<boolean>(true);
const [liked, setLiked] = useState<boolean>(false);
const [duration, setDuration] = useState<number | null>(null);
const [position, setPosition] = useState<number | null>(null);
const { songId } = useContext(AppContext);
const { data, error } = useQuery(SongQuery, {
variables: { _id: songId },
});
useEffect(() => {
if (data && data.song) {
setSong(data.song);
}
}, [data]);
useEffect(() => {
if (song) {
playCurrentSong();
}
}, [song]);
const playCurrentSong = async () => {
if (sound) {
await sound.unloadAsync();
}
const { sound: newSound } = await Sound.createAsync(
{ uri: song.soundUri },
{ shouldPlay: isPlaying }
);
console.log("sound" + newSound);
setSound(newSound);
};
const onPlayPausePress = async () => {
if (!sound) {
console.log("no sound");
return;
}
if (isPlaying) {
await sound.pauseAsync();
} else {
await sound.playAsync();
}
};
const onLikeSong = async () => {
try {
setLiked(true);
} catch (e) {
console.log(e);
}
};
const getProgress = () => {
if (sound === null || duration === null || position === null) {
return 0;
}
return (position / duration) * 100;
};
const onPlaybackStatusUpdate = (status) => {
setIsPlaying(status.isPlaying);
setDuration(status.durationMillis);
setPosition(status.positionMillis);
};
}
Weirdly enough, the log after the function does not even work, it is never logged. I don't get any errors though, making it quite hard to debug this where it goes wrong, the URI is working and pointing towards an mp3 file, and the state is set correctly. Any pointers how i could debug this further?

WebRTC in react-native (hooks), redux - Unhandled Promise Rejections

I'm developing a react-native application, which uses webRTC.
I extremely liked the minimal version I found here (kudos to baconcheese113!) and I decided to refactor it to create my react component.
I have set up a backend (DynamoDB, Appsync) and a redux store that allows me to:
dispatch an action sendCreateUserControlMsg, which down the line calls the Appsync endpoint to create a new ControlUserMsg
subscribe to a ControlUserMsg, set the flag triggerWebrtcData and save webrtcData in the Redux state
The following component (which for now calls itself), sometimes works, but mostly doesn't. I feel that the problem is related to JS Promises, but I do not fully understand how I should design the component to avoid race conditions.
import React, { useState, useEffect } from 'react';
import { View, SafeAreaView, Button, StyleSheet } from 'react-native';
import { RTCPeerConnection, RTCView, mediaDevices } from 'react-native-webrtc';
import { sendCreateUserControlMsg } from '../redux/actions/UserControlMsgActions';
import controlMsgActions from './../model/control_msg_actions';
import webrtcActionTypes from './../model/webrtc_action_types';
import { useDispatch, useSelector } from "react-redux";
import * as triggersMatch from '../redux/actions/TriggersMatchActions';
var IS_LOCAL_USER = true //manual flag I temporarily set
var localUserID = '00';
var localUser = 'localUser'
var remoteUserID = '01';
var remoteUser = 'remoteUser'
if (IS_LOCAL_USER) {
var matchedUserId = remoteUserID
var user_id = localUserID;
var user = localUser
}
else {
var matchedUserId = localUserID
var user_id = remoteUserID;
var user = remoteUser
}
export default function App() {
const dispatch = useDispatch();
var triggersMatchBool = useSelector(state => state.triggers_match)
var webrtcData = useSelector(state => state.webrtc_description.webrtcData)
const [localStream, setLocalStream] = useState();
const [remoteStream, setRemoteStream] = useState();
const [cachedLocalPC, setCachedLocalPC] = useState();
const [cachedRemotePC, setCachedRemotePC] = useState();
const sendICE = (candidate, isLocal) => {
var type
isLocal ? type = webrtcActionTypes["NEW_ICE_CANDIDATE_FROM_LOCAL"] : type = webrtcActionTypes["NEW_ICE_CANDIDATE_FROM_REMOTE"]
var payload = JSON.stringify({
type,
candidate
})
console.log(`Sending ICE to ${matchedUserId}`)
dispatch(sendCreateUserControlMsg(matchedUserId, user_id, user, payload, controlMsgActions["WEBRTC_DATA"]));
}
const sendOffer = (offer) => {
type = webrtcActionTypes["OFFER"]
var payload = JSON.stringify({
type,
offer
})
console.log(`Sending Offer to ${matchedUserId}`)
dispatch(sendCreateUserControlMsg(matchedUserId, user_id, user, payload, controlMsgActions["WEBRTC_DATA"]));
}
const sendAnswer = (answer) => {
type = webrtcActionTypes["ANSWER"]
var payload = JSON.stringify({
type,
answer
})
console.log(`Sending answer to ${matchedUserId}`)
dispatch(sendCreateUserControlMsg(matchedUserId, user_id, user, payload, controlMsgActions["WEBRTC_DATA"]));
}
const [isMuted, setIsMuted] = useState(false);
// START triggers
async function triggerMatchWatcher() {
if (triggersMatchBool.triggerWebrtcData) {
dispatch(triggersMatch.endTriggerWebrtcData());
switch (webrtcData.type) {
case webrtcActionTypes["NEW_ICE_CANDIDATE_FROM_LOCAL"]:
try {
setCachedRemotePC(cachedRemotePC.addIceCandidate(webrtcData.candidate))
} catch (error) {
console.warn('ICE not added')
}
break;
case webrtcActionTypes["NEW_ICE_CANDIDATE_FROM_REMOTE"]:
try {
setCachedLocalPC(cachedLocalPC.addIceCandidate(webrtcData.candidate))
} catch (error) {
console.warn('ICE not added')
}
break;
case webrtcActionTypes["OFFER"]:
console.log('remotePC, setRemoteDescription');
try {
await cachedRemotePC.setRemoteDescription(webrtcData.offer);
console.log('RemotePC, createAnswer');
const answer = await cachedRemotePC.createAnswer();
setCachedRemotePC(cachedRemotePC)
sendAnswer(answer);
} catch (error) {
console.warn(`setRemoteDescription failed ${error}`);
}
case webrtcActionTypes["ANSWER"]:
try {
console.log(`Answer from remotePC: ${webrtcData.answer.sdp}`);
console.log('remotePC, setLocalDescription');
await cachedRemotePC.setLocalDescription(webrtcData.answer);
setCachedRemotePC(cachedRemotePC)
console.log('localPC, setRemoteDescription');
await cachedLocalPC.setRemoteDescription(cachedRemotePC.localDescription);
setCachedLocalPC(cachedLocalPC)
} catch (error) {
console.warn(`setLocalDescription failed ${error}`);
}
}
}
}
useEffect(() => {
triggerMatchWatcher()
}
);
const startLocalStream = async () => {
// isFront will determine if the initial camera should face user or environment
const isFront = true;
const devices = await mediaDevices.enumerateDevices();
const facing = isFront ? 'front' : 'environment';
const videoSourceId = devices.find(device => device.kind === 'videoinput' && device.facing === facing);
const facingMode = isFront ? 'user' : 'environment';
const constraints = {
audio: true,
video: {
mandatory: {
minWidth: 500, // Provide your own width, height and frame rate here
minHeight: 300,
minFrameRate: 30,
},
facingMode,
optional: videoSourceId ? [{ sourceId: videoSourceId }] : [],
},
};
const newStream = await mediaDevices.getUserMedia(constraints);
setLocalStream(newStream);
};
const startCall = async () => {
const configuration = { iceServers: [{ url: 'stun:stun.l.google.com:19302' }] };
const localPC = new RTCPeerConnection(configuration);
const remotePC = new RTCPeerConnection(configuration);
localPC.onicecandidate = e => {
try {
console.log('localPC icecandidate:', e.candidate);
if (e.candidate) {
sendICE(e.candidate, true)
}
} catch (err) {
console.error(`Error adding remotePC iceCandidate: ${err}`);
}
};
remotePC.onicecandidate = e => {
try {
console.log('remotePC icecandidate:', e.candidate);
if (e.candidate) {
sendICE(e.candidate, false)
}
} catch (err) {
console.error(`Error adding localPC iceCandidate: ${err}`);
}
};
remotePC.onaddstream = e => {
console.log('remotePC tracking with ', e);
if (e.stream && remoteStream !== e.stream) {
console.log('RemotePC received the stream', e.stream);
setRemoteStream(e.stream);
}
};
localPC.addStream(localStream);
// Not sure whether onnegotiationneeded is needed
// localPC.onnegotiationneeded = async () => {
// try {
// const offer = await localPC.createOffer();
// console.log('Offer from localPC, setLocalDescription');
// await localPC.setLocalDescription(offer);
// sendOffer(localPC.localDescription)
// } catch (err) {
// console.error(err);
// }
// };
try {
const offer = await localPC.createOffer();
console.log('Offer from localPC, setLocalDescription');
await localPC.setLocalDescription(offer);
sendOffer(localPC.localDescription)
} catch (err) {
console.error(err);
}
setCachedLocalPC(localPC);
setCachedRemotePC(remotePC);
};
const switchCamera = () => {
localStream.getVideoTracks().forEach(track => track._switchCamera());
};
const closeStreams = () => {
if (cachedLocalPC) {
cachedLocalPC.removeStream(localStream);
cachedLocalPC.close();
})
}
if (cachedRemotePC) {
cachedRemotePC.removeStream(localStream);
cachedRemotePC.close();
})
}
setLocalStream();
setRemoteStream();
setCachedRemotePC();
setCachedLocalPC();
};
return (
<SafeAreaView style={styles.container}>
{!localStream && <Button title="Click to start stream" onPress={startLocalStream} />}
{localStream && <Button title="Click to start call" onPress={startCall} disabled={!!remoteStream} />}
{localStream && (
<View style={styles.toggleButtons}>
<Button title="Switch camera" onPress={switchCamera} />
</View>
)}
<View style={styles.rtcview}>
{localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
</View>
<View style={styles.rtcview}>
{remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
</View>
<Button title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
// omitted
});
The most common errors I receive are:
Error: Failed to add ICE candidate
Possible Unhandled Promise Rejection
and
setLocalDescription failed TypeError: Cannot read property 'sdp' of
undefined
If I console.log I can see that are JS Promise, but since are not a functions I cannot use .then().
How can I call the addIceCandidate method or setLocalDescription method without incurring in the Unhandled Promise Rejection errors?
What are the best practices to work with WebRTC in react-native?

Vue + SSR | How to transfer mixin to config file?

I am writing a config for ssr
Added mixin, to replace the title and meta Announced it globally in the app.js file.
import headMixin from './util/title'
Vue.mixin(headMixin);
When you first load the page, or when you go to the root of the site, it works.
If you go to another page, it does not work (
I wanted to add it to the config file entry-client.js in the function router.onReady()
import Vue from 'vue'
import 'es6-promise/auto'
import {createApp} from './app'
import ProgressBar from './components/ProgressBar.vue'
const bar = Vue.prototype.$bar = new Vue(ProgressBar).$mount();
document.body.appendChild(bar.$el);
Vue.mixin({
beforeRouteUpdate(to, from, next) {
const {asyncData} = this.$options;
if (asyncData) {
asyncData({
store: this.$store,
route: to
}).then(next).catch(next)
} else {
next()
}
}
});
const {app, router, store} = createApp();
if (window.__INITIAL_STATE__) {
store.replaceState(window.__INITIAL_STATE__)
}
router.onReady(() => {
router.beforeResolve((to, from, next) => {
const matched = router.getMatchedComponents(to);
const prevMatched = router.getMatchedComponents(from);
let diffed = false;
const activated = matched.filter((c, i) => {
return diffed || (diffed = (prevMatched[i] !== c))
});
const asyncDataHooks = activated.map(c => c.asyncData).filter(_ => _);
if (!asyncDataHooks.length) {
return next()
}
// TODO Обсудить наличие статусбара
bar.start();
Promise.all(asyncDataHooks.map(hook => hook({ store, route: to })))
.then(() => {
bar.finish();
next()
})
.catch(next)
});
app.$mount('#app')
});
But I can not understand how to do it correctly (
Himself mixin here
const cleanMetas = () => {
return new Promise((resolve, reject) => {
const items = document.head.querySelectorAll('meta');
for (const i in items) {
if (typeof items[i] === 'object'
&& ['viewport'].findIndex(val => val === items[i].name) !== 0
&& items[i].name !== '')
document.head.removeChild(items[i])
}
resolve()
})
};
const createMeta = (vm, name, ...attr) => {
const meta = document.createElement('meta');
meta.setAttribute(name[0], name[1]);
for (const i in attr) {
const at = attr[i];
for (const k in at) {
meta.setAttribute(at[k][0], getString(vm, at[k][1]))
}
}
document.head.appendChild(meta);
};
const getString = (vm, content) => {
return typeof content === 'function'
? content.call(vm)
: content
};
export const getMeta = (vm, meta, env) => {
if (typeof meta !== 'object')
return;
if (env) {
return Object.keys(meta)
.map(value => {
return Object.keys(meta[value])
.map(key => `${key}="${getString(vm, meta[value][key])}"`)
.join(" ");
})
.map(value => ` <meta ${value} >`)
.join("\n");
} else {
return meta
}
};
const serverHeadMixin = {
created() {
const {head} = this.$options;
if (head) {
const {title} = head;
if (title)
this.$ssrContext.title = getString(this, title);
const {meta} = head;
if (meta)
this.$ssrContext.meta = `\n${getMeta(this, meta, true)}`
}
}
};
const clientHeadMixin = {
mounted() {
const vm = this;
const {head} = this.$options;
if (head) {
const {title} = head;
if (title) {
document.title = getString(this, title)
}
}
if (head) {
cleanMetas().then(() => {
const {meta} = head;
if (meta)
for (const nm in meta) {
const name = Object.entries(meta[nm])[0];
const attr = Object.entries(meta[nm]).splice(1, Object.entries(meta[nm]).length);
createMeta(vm, name, attr)
}
})
}
}
};
export default process.env.VUE_ENV === 'server'
? serverHeadMixin
: clientHeadMixin
Link to repository with full config