Vuejs: How to pass data to a non-related component?

I need to display an image, title and text for the particular recipe that I clicked on.

I have ItemSwiper (parent):

<template>
     <Slide
         v-for="recipe in storeRecipe.data"
         :key="recipe.recipe_id">
         <ItemCard :data="recipe" :pending="storeRecipe.pending" />
     </Slide>
</template>

<script setup>
import { onMounted } from 'vue';
import { useStoreRecipe } from '@/store/storeRecipe';
import ItemCard from '@/component/ItemCard.vue';

// Pinia store
const storeRecipe = useStoreRecipe();

onMounted(async () => {
    await storeRecipe.loadRecipes();
});
</script>

Then in ItemCard (child):

<template>
    <div class="card">
        <div class="card__item">
            <img
                class="card__image"
                :src="getSrc('.jpg')"
                :alt="data.alt"/>
            <div class="card__content">
                <h2 class="card__title">{{ data.title }}</h2>
                <p class="card__text">{{ data.short_description }}</p>
                <router-link
                    class="card__link"
                    :to="{
                        name: 'recipeDetail',
                        params: { recipe: data.slug },
                    }"
                    >View more</router-link
                >
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted } from 'vue';

const props = defineProps(['data', 'pending']);

const getSrc = ext => {
    return new URL(
        `../assets/images/content/recipe/${props.data.image}${ext}`,
        import.meta.url
    ).href;
};

onMounted(() => {
    const img = new Image(getSrc('.jpg'));
    img.onload = () => {
        isLoaded.value = true;
    };
    img.src = getSrc('.jpg');
});
</script>

And when I click on this ‘View More’ router-link, I go to the recipe detail page (ViewRecipeDetail):

<template>
    <img
        class="card__image"
        :src="getSrc('.jpg')"
        :alt="storeRecipe.data.alt" />

    <div class="card__content">
        <h2 class="card__title">
            {{ storeRecipe.data.title }}
        </h2>
        <p class="card__text">
            {{ storeRecipe.data.short_description }}
        </p>
    </div>
</template>

<script setup>
import { useStoreRecipe } from '@/store/storeRecipe';
const storeRecipe = useStoreRecipe();
</script>

I want to be able to see the same image, title and other data in ViewRecipeDetail that was on the card in ItemCard. I don’t understand how to do so, if ViewRecipeDetail is not related to ItemCard. All ItemCard has is just a router-link to this component. Also, I need to get access to getSrc in ViewRecipeDetail somehow as well without duplicating the code. Using a composable seems quite difficult.

Please, give me a possible solution. If there’s any way to just use store, without query params on router-link, it would be great as well.

Combine subjects in RxJS similar to zip

I want to combine two subjects in similar way as zip does, but with the following important difference.

I want an observables that combines two subjects in this way. When both have emitted values, emit the latest of their values. Then, both need to emit at least once again, then emit their latest emitted values. Etc.

Both subjects:

1 ———- 2 —– 3 — 4 ——————- 5 ——

——- a ——————- b — c — d —-————

Goal observable:

——- 1a —————– 4b —————-5d —-

Simple example: subject1 emits 5 times and after that subject2 emits once. The first emitted value of zip is a pair of both first emits of the subjects. I want (subj1-emit5, subj2-emit1).

Animation in React Native not displaying on screen load on Android only

I’m getting a behaviour I wasn’t expecting in my React Native project using Animation.View on Android.

React-native 0.72

I’m loading a screen MyProfile and showing up user’s info and badges. When I press on a badge it opens a Popup component that displays as children a BadgePopUp component that displays badge’s info with multiple animations for each element.

It works nice except if I press on the badge immediately when badges are shown (page might still be loading). By using console.logs I see that it waits for page to fully load and then launches the pop up thus creating a slight delay.

I’m ok with it but the problem is it opens the pop up all blank then after the timing of the animations it shows the items (sometimes only the badge img is delayed). Then if I close it and press it again, or if on screen load I wait a coupla seconds before I press on it, it works fine.

This does not happen in ios, only in android, and only in this page, not in the rest of the screens.

My implementation:

MyProfile.js:

...
const MyProfile = () => {
  const { user, favoriteCourts, addedCourts, badges } = useSelector(
    state => state.userReducer,
  );

  ...

  const verifiedBadges = JSON.parse(Storage.getString('badges'));
  const getVerifiedBadge = badgeId => {
    const badge = verifiedBadges?.find(item => item.id === badgeId);
    return badge;
  };
  const badge = getVerifiedBadge(user?.user_badge_id);

  ...

  const [isPopUpVisible, setIsPopUpVisible] = useState(false);
  const [highestLevelBadges, setHighestLevelBadges] = useState(
    getHighestLevelBadges(badges),
  );
  const [badgeDetailsToDisplay, setBadgeDetailsDataToDisplay] = useState(null);

  ...

  const handleMyBadges = () => {
    navigation.navigate('MyBadges');
  };

  const handleBadgeDetails = (
    badgeLevel,
    badgeImg,
    badgeName,
    badgeQuantity,
    badgeDescription,
  ) => {
    setBadgeDetailsDataToDisplay({
      badgeLevel: badgeLevel,
      badgeImg: badgeImg,
      badgeName: badgeName,
      badgeQuantity: badgeQuantity,
      badgeDescription: badgeDescription,
    });

    setIsPopUpVisible(true);
  };

  const getBadgeQuantityText = actionName => {
    switch (actionName) {
      case 'court_registrations':
        return `${addedCourts?.length} ${t('Court_hunter_add_info')}`;
        break;
      case 'court_checkins':
        return `${user?.num_checkins} ${t('King_of_the_court_add_info')}`;
        break;
      default:
        return t('Court_hunter_add_info');
        break;
    }
  };

  const handleBadgesToDisplay = () => {
    badgesToDisplay = highestLevelBadges.map((badge, index) => {
      const badgeImageSource = gatBadgeImage(badge.id);

      const badgeLevel = getBadgeLevelName(badge.options.level);
      const badgeName =
        badge.options.action_name === 'court_registrations'
          ? t('Court_hunter')
          : badge.name.split(' - ', 1);
      const badgeQuantity = getBadgeQuantityText(badge.options.action_name);
      const badgeDescription =
        lang !== 'en-US' ? badge.description : badge.description_en;

      return (
        <View key={index} style={{ left: 4, marginHorizontal: 10 }}>
          <ContainedImage
            image={badgeImageSource}
            size={'extra-small'}
            action={() => {
              console.log('pressed on badge');
              handleBadgeDetails(
                badgeLevel,
                badgeImageSource,
                badgeName,
                badgeQuantity,
                badgeDescription,
              );
            }}
          />
        </View>
      );
    });

    return badgesToDisplay;
  };

  useEffect(() => {
    console.log('isFocused, navigationState');

    const scrollIfNeeded = () => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollTo({ y: 0, animated: true });
      }
    };

    // Get the current screen's route key
    const currentRouteKey = navigationState.routes[navigationState.index].key;

    // Check if the tab is focused and the current screen is the starting screen
    const isTabFocused = isFocused && currentRouteKey === 'StartingScreen';

    if (isTabFocused) {
      scrollIfNeeded();
    }
  }, [isFocused, navigationState]);

  useEffect(() => {
    console.log('in addedCourts, favoriteCourts useEffect');
    if (addedCourts !== null && favoriteCourts !== null && user !== null) {
      setFavCourtsToSend(favoriteCourts);
      handleGetMyEvents();
      setIsLoading(false);
    }
  }, [addedCourts, favoriteCourts]);

  useEffect(() => {
    console.log('in events and filteredEvents useEffect');
    if (events && !filteredEvents) {
      setFilteredEvents(filterEventsByDate(events));
    }
  }, [events, filteredEvents]);

  return (
    <FullContainer
      header={true}
      hasActions={true}
      logo={true}
      hasBackButton={false}
      hideSearch={true}
      hideAddCourt={true}
      showConfig={true}
      hasNotifications={true}>
      {isPageLoading && <LoaderView />}
      {isPopUpVisible === true && badgeDetailsToDisplay !== null && (
        <PopUp
          visible={isPopUpVisible}
          onClose={() => {
            setIsPopUpVisible(false);
          }}
          fixedHeight={true}
          hasDarkTransparency={true}>
          <BadgePopUp
            title={badgeDetailsToDisplay.badgeName}
            image={badgeDetailsToDisplay.badgeImg}
            badgeName={badgeDetailsToDisplay.badgeLevel}
            additionalInfo={badgeDetailsToDisplay.badgeQuantity}
            description={badgeDetailsToDisplay.badgeDescription}
            hasAnimations={true}
          />
        </PopUp>
      )}
      <AlertModal
        modalVisible={modalVisible}
        setModalVisible={setModalVisible}
        title={modalTitle}
        text={modalText}
        hasCloseButton={true}
      />
      <ScrollView
        ref={scrollViewRef}
        style={[{ paddingHorizontal: 0 }, Styles.flexOne]}
        showsVerticalScrollIndicator={false}>
        <View
          style={[
            ProfilePageStyles.profileInfoContainer,
            ProfilePageStyles.paddingPage,
          ]}>
          <Text style={ProfilePageStyles.title}>{t('tab_profile')}</Text>
          <View style={ProfilePageStyles.profileHeaderContainer}>
            <View style={ProfilePageStyles.boxPicture}>
              <CircleDisplay
                size={'small'}
                pressable={false}
                type={'image'}
                src={user?.picture_url}
                colorType={'grey'}
              />
            </View>

            <View style={ProfilePageStyles.boxSocialBar}>
              <SocialBar
                checkins={user?.num_checkins}
                followers={user?.num_followers}
                following={user?.num_following}
                onPress={handleGoToFollowersPage}
              />
            </View>
          </View>
          <View style={Styles.flexRow}>
            <Text style={ProfilePageStyles.labelBold}>
              {user?.first_name} {user?.last_name}
            </Text>
            {user?.user_badge_id && (
              <Pressable
                onPress={() => {
                  handleToast(
                    lang === 'en-US' ? badge.description_en : badge.description,
                    badge.name,
                    'gray',
                  );
                }}
                style={[
                  ProfilePageStyles.badgePressable,
                  { backgroundColor: badge?.hex_color },
                ]}>
                <Text style={ProfilePageStyles.badgeText}>{badge?.name}</Text>
              </Pressable>
            )}
          </View>

          <Text style={ProfilePageStyles.labelRegular}>@{user?.username}</Text>

          <Text style={[ProfilePageStyles.labelRegular, { marginTop: 6 }]}>
            {user?.profile_info}
          </Text>
          <View style={ProfilePageStyles.profileEditContainer}>
            <HoopersButton
              size={'small'}
              theme1={'primary'}
              onPress1={() => {
                handleEditProfile();
              }}
              text1={t('Edit_profile')}
            />
          </View>
        </View>

        <View style={{ paddingBottom: 20, backgroundColor: Colors.HPS_WHITE }}>
          <View
            style={[
              Styles.alignDisplayFlexRow,
              Styles.rowStartCenter,
              ProfilePageStyles.paddingPage,
            ]}>
            <Text style={[ProfilePageStyles.labelBold, { marginRight: 8 }]}>
              {t('My_badges')}
            </Text>
            <HoopersButton
              size={'tiny'}
              theme1={'outline'}
              onPress1={() => {
                handleMyBadges();
              }}
              text1={t('See_all')}
            />
          </View>
          {badges.length > 0 ? (
            <View style={[Styles.alignDisplayFlexRow, Styles.rowStartCenter]}>
              <ScrollView
                horizontal={true}
                style={{ width: width, marginTop: 13 }}>
                {handleBadgesToDisplay()}
              </ScrollView>
            </View>
          ) : (
            <View style={[Styles.center, { marginTop: 13 }]}>
              <Text style={ProfilePageStyles.labelRegular}>
                {t('User_has_no_badges')}
              </Text>
            </View>
          )}
        </View>

        <View style={ProfilePageStyles.profileCourtsContainer}>
          {isLoading && <LoaderView color={Colors.HPS_OFWHITE} />}
          {!isLoading && renderAddedCourtsSection()}
          {!isLoading && renderFavoriteCourtsSection()}
          {!isLoading && filteredEvents && renderEventsSection()}
        </View>
      </ScrollView>
    </FullContainer>
  );
};

export default MyProfile;

PopUp.js:

...
const PopUp = ({
  onClose,
  children,
  visible,
  fixedHeight,
  hasDarkTransparency,
  hasConfettis,
}) => {
  const { width, height } = useWindowDimensions();

  const confettiRef = useRef(null);

  useEffect(() => {
    if (visible && hasConfettis && confettiRef.current) {
      confettiRef.current.start();
    }
  }, [visible]);

  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={visible}
      onRequestClose={onClose}>
      <View
        style={[
          PopUpStyles.container,
          hasDarkTransparency
            ? {
                backgroundColor: Colors.darkTransparency,
              }
            : {
                backgroundColor: Colors.lightTransparency,
              },
        ]}>
        <View
          style={[
            PopUpStyles.secondContainer,
            { width: width },
            fixedHeight === true && { height: height * 0.8, maxHeight: 600 },
          ]}>
          <View
            style={[
              PopUpStyles.popup,
              {
                width: width * 0.85,
                maxWidth: 400,
              },
            ]}>
            <Pressable
              style={{
                position: 'absolute',
                zIndex: 99,
                right: -10,
                top: -10,
              }}
              onPress={onClose}>
              <Icon
                name="closeCircle"
                width="30"
                height="30"
                fill={Colors.HPS_ORANGE}
                stroke={Colors.HPS_GREY}
              />
            </Pressable>
            {children}
          </View>
        </View>
      </View>
      {hasConfettis && (
        <ConfettiCannon
          ref={confettiRef}
          count={120} // Number of confetti particles
          origin={{ x: -10, y: 0 }} // Starting position (in this case, bottom-left corner)
          autoStart={true} // Don't auto-start confetti, start it manually after other animations
          fadeOut={true} // Make confetti fade out after some time
        />
      )}
    </Modal>
  );
};

export default PopUp;

BadgePopUp.js:

const BadgePopUp = ({
  title,
  subtitle,
  image,
  badgeName,
  additionalInfo,
  description,
  action,
  hasAnimations,
}) => {
  console.log('BadgePopUp: Rendering component');
  
  ...

  const spinValue = useRef(new Animated.Value(0.01)).current;
  const scaleValue = useRef(new Animated.Value(2.5)).current;
  const laterOpacityAnimValue = useRef(new Animated.Value(0.01)).current;
  const firstOpacityAnimValue = useRef(new Animated.Value(0.01)).current;
  const slideDownValue = useRef(new Animated.Value(-70)).current;
  const slideRightValue = useRef(new Animated.Value(-200)).current;
  const slideLeftValue = useRef(new Animated.Value(200)).current;

  const setAnimation = (toValue, duration, easing, useNativeDriver) => {
    return {
      toValue: toValue,
      duration: duration,
      easing: easing,
      useNativeDriver: useNativeDriver,
    };
  };

  const renderImage = () => {
    return <Image source={image} width={130} height={130} />;
  };

  useEffect(() => {
    if (hasAnimations === true && image) {
      Animated.parallel([
        Animated.sequence([
          Animated.delay(100),
          Animated.timing(firstOpacityAnimValue, {
            toValue: 1,
            duration: 500,
            easing: Easing.ease,
            useNativeDriver: true,
          }),
        ]),
        Animated.sequence([
          Animated.delay(200),
          Animated.timing(laterOpacityAnimValue, {
            toValue: 1,
            duration: 350,
            easing: Easing.ease,
            useNativeDriver: true,
          }),
        ]),
        Animated.timing(spinValue, {
          toValue: 1,
          duration: 500,
          easing: Easing.ease,
          useNativeDriver: true,
        }),
        Animated.timing(scaleValue, {
          toValue: 1,
          duration: 500,
          easing: Easing.ease,
          useNativeDriver: true,
        }),
        Animated.timing(slideDownValue, {
          toValue: 1,
          duration: 350,
          easing: Easing.ease,
          useNativeDriver: true,
        }),
        Animated.timing(slideRightValue, {
          toValue: 1,
          duration: 500,
          easing: Easing.ease,
          useNativeDriver: true,
        }),
        Animated.timing(slideLeftValue, {
          toValue: 1,
          duration: 500,
          easing: Easing.ease,
          useNativeDriver: true,
        }),
      ]).start(() => {
        console.log('BadgePopUp: Animations completed');
      });
    }
  }, [
    spinValue,
    scaleValue,
    laterOpacityAnimValue,
    firstOpacityAnimValue,
    slideDownValue,
    slideRightValue,
    slideLeftValue,
    hasAnimations,
    image,
  ]);

  const spin = spinValue.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <>
      <View
        style={[
          BadgePopUpStyles.container,
          {
            alignItems: 'center',
            justifyContent: 'space-around',
            maxHeight: propsVol > 5 ? 500 : 400,
          },
        ]}>
        {title && (
          <View style={BadgePopUpStyles.titleContainer}>
            {hasAnimations === true ? (
              <Animated.View
                style={{
                  transform: [{ translateY: slideDownValue }],
                  opacity: firstOpacityAnimValue,
                }}>
                <Text style={BadgePopUpStyles.title}>{title}</Text>
              </Animated.View>
            ) : (
              <Text style={BadgePopUpStyles.title}>{title}</Text>
            )}
          </View>
        )}
        {subtitle && (
          <View style={BadgePopUpStyles.subtitleContainer}>
            {hasAnimations === true ? (
              <Animated.View
                style={{
                  transform: [{ translateX: slideRightValue }],
                  opacity: laterOpacityAnimValue,
                }}>
                <Text style={BadgePopUpStyles.subtitle}>{subtitle}</Text>
              </Animated.View>
            ) : (
              <Text style={BadgePopUpStyles.subtitle}>{subtitle}</Text>
            )}
          </View>
        )}
        {image && (
          <>
            {hasAnimations === true ? (
              <Animated.View
                style={{
                  transform: [{ rotate: spin }, { scale: scaleValue }],
                  opacity: laterOpacityAnimValue,
                }}>
                <View style={BadgePopUpStyles.imageContainer}>
                  {renderImage()}
                </View>
              </Animated.View>
            ) : (
              <View style={BadgePopUpStyles.imageContainer}>
                {renderImage()}
              </View>
            )}
          </>
        )}
        {(badgeName || additionalInfo) && (
          <View style={BadgePopUpStyles.badgeContainer}>
            {badgeName &&
              (hasAnimations === true ? (
                <Animated.View
                  style={{
                    transform: [{ translateX: slideRightValue }],
                    opacity: laterOpacityAnimValue, // Apply opacity animation to ContainedImage
                  }}>
                  <Text
                    style={[BadgePopUpStyles.subtitle, { marginBottom: 5 }]}>
                    {badgeName}
                  </Text>
                </Animated.View>
              ) : (
                <Text style={[BadgePopUpStyles.subtitle, { marginBottom: 5 }]}>
                  {badgeName}
                </Text>
              ))}
            {additionalInfo &&
              (hasAnimations === true ? (
                <Animated.View
                  style={{
                    transform: [{ translateX: slideLeftValue }],
                    opacity: laterOpacityAnimValue,
                  }}>
                  <Text style={BadgePopUpStyles.description}>
                    {additionalInfo}
                  </Text>
                </Animated.View>
              ) : (
                <Text style={BadgePopUpStyles.description}>
                  {additionalInfo}
                </Text>
              ))}
          </View>
        )}

        {description && (
          <View style={BadgePopUpStyles.descriptionContainer}>
            {hasAnimations === true ? (
              <Animated.View
                style={{
                  transform: [{ translateX: slideRightValue }],
                  opacity: laterOpacityAnimValue,
                }}>
                <Text style={BadgePopUpStyles.description}>{description}</Text>
              </Animated.View>
            ) : (
              <Text style={BadgePopUpStyles.description}>{description}</Text>
            )}
          </View>
        )}

        {action &&
          (hasAnimations === true ? (
            <Animated.View
              style={{
                opacity: laterOpacityAnimValue,
              }}>
              <TextLink
                text={action.title ? action.title : 'See more'}
                type={'orange'}
                size={16}
                onPress={action.onPress}
              />
            </Animated.View>
          ) : (
            <TextLink
              text={action.title ? action.title : 'See more'}
              type={'orange'}
              size={16}
              onPress={action.onPress}
            />
          ))}
      </View>
    </>
  );
};

export default BadgePopUp;

Any idea why this might be happening?

Using map in JSX producing undefined items

I’m trying to generate <Audio> components with map:

import React, { useState, useRef, createRef } from 'react';

const audios = [{ src: '/fire.mp3' }, { src: '/crickets.mp3' }];

function Audio({ audioRef }) {
  const { src, ref } = audioRef;

  function handleVolumeChange(value) {
    ref.current.volume = value / 100;
  }

  return (
    <audio ref={ref} loop>
      <source src={src} type="audio/mpeg" /> Your browser does not support the
      audio element.
    </audio>
  );
}

export const App = ({ name }) => {
  const audioRefs = useRef(
    audios.map((audio) => ({
      ...audio,
      ref: createRef(),
    }))
  );
    
  return (
    <>
      {audioRefs.current.map((audioRef, index) => (
        <Audio key={audioRef.src} audio={audioRef} />
      ))}
    </>
  );
};

However, I’m getting this error:

Cannot destructure property ‘src’ of ‘audioRef’ as it is undefined.

Why is audioRef undefined when audioRefs is an array?

[{…}, {…}]
  0: Object
    ref: Object
    src: "/fire.mp3"
    <prototype>: Object
  1: Object
    ref: Object
    src: "/crickets.mp3"
    <prototype>: Object

Working code on StackBlitz.

Note: I need the ref to control the volume of the <audio> element.

Objects are not valid as a React child (found: object with keys {parameterId, parameterName, parameterValue})

I get Objects are not valid as a React child (found: object with keys {parameterId, parameterName, parameterValue}). If you meant to render a collection of children, use an array instead. whenever the editData.parameter is not equal to null. How do I fix this? I have tried numerous of bug fixing but it is not accepting my code.

<Autocomplete
              options={params}
              getOptionLabel={(option) =>
                `${option.parameterName} - ${option.parameterValue}`
              }
              value={editData.parameters || null}
              onChange={handleAddParamChange}
              isOptionEqualToValue={(option, value) =>
                option.parameterId === value.parameterId
              }
              sx={{ width: "88.5%", mb: 2 }}
              renderInput={(params) => (
                <TextField {...params} label="Select Parameter" />
              )}
            />

It should be accepting the data even when the editData.parameter is not null. Can anyone help me?

Dynamic Multiple Font load as per env file

I’ve one file font.css where multiple fonts are loaded but i need to make dynamic font path as per the env file so how can we achieve that in react

You can suggest me the feasible solutions.

I’ve tried by creating an font.scss file and declared global variable in the default.js
which i’m trying to access in scss but unable to get

Create a canvas with layer management

I want to integrate a fully working canvas in my Next.js application with the feature to add layers over the canvas such that each layer can have it’s own strokes (made by the user) and images (uploaded by the user). Of course just like any canvas application, it should have the feature to draw strokes, erase them and drag and resize uploaded images as well. The user should also be able to rearrange layers as to their liking.

Initially I tried using fabric.js canvas library since it’s quite powerful and offers features like dragging and rotating objects in the canvas with ease. The only problem with it is that it does not have an in-built layer management system. It puts all of the objects in the canvas in a stack-like list where the position of the object in the list determines it’s z-index position in the canvas. So no two objects can ever be in the same layer. Although we can send objects down a layer or up a layer but there is no dedicated layer management.

Next up, I used konva.js. It has an in-built layer management system where any update to a single layer should not re-render the entire canvas but should only updated the affected layer. But I found the eraser to just overdraw over the canvas with the background color of the canvas even if we use destination-out as a globalCompositeOperation. This is in fact demonstrated when we erase some stroke on the canvas and then drag an image in the area where the stroke was erased. The image gets covered by the strokes made by the eraser even though they are in the same layer.
Here by attached is a GIF to demonstrate the same

Find element of class type at scroll position

Most questions about CSS positioning tend to ask “what is the position of element X” – however I would like to know “what element is at position x”?

I have a scroll window in which I basically want to know which div is no longer visible and which is the first div visible. Is it possible? Is there effectively a selector for $('div.class atScrollPosition X') in Jquery or Vanilla JS. Really don’t mind.

No results from MSGraph when attempting to retrieve anything using bearer token

I’m attempting to get anything from MSGraph using a bearer token: emails, events etc.
I have:

  1. Made sure the app has the permissions to do whatever it needs to.
  2. Tested without using a token to get my emails and SharePoint list items and this works.
  3. Tested the token on Postman and it works successfully to get what I need USING the token.
    It’s just that the code does NOT work:

Here is the function that successfully gets a token and following that, the function that retrieves the events:

export const getToken = async (msGraphcontext: any): Promise<string> => {
  try {
    tokenProvider = await msGraphcontext.aadTokenProviderFactory.getTokenProvider();
    const accessToken: string = await tokenProvider.getToken(_.TOKEN_API, false);
    return `Bearer ${accessToken}`;
  } catch (err) {
    console.log('getToken:=> ' + JSON.stringify(err));
    throw (err);
  }
}

export const retrieveEvents = async (msGraphcontext: any) => {
  try {
    const token = await getToken(msGraphcontext);
    return await client.api('/me/events').headers({
        'Authorization': `${token}`,
        'Content-Type': 'application/json'

    }).get()
  } catch (err) {
    console.log(err, 'err');
  }
};

Can anyone see something wrong with what I’m doing. Please note, that the token is valid but I receive just TypeError: Cannot read properties of undefined (reading 'api') from the console.

This ajax function is not running in cakephp 4

$.ajax({
        type: "POST",
        url: '/Generals/checkUserAvailability',
        data: "mobile=" + mobile + "&email_id=" + email,
        success: "success",
        dataType: 'text',
        context: document.body
      }).done(function(msg) {
        if (msg == 'true') {
          $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: data,
          }).done(function(msg) {
            $('.' + currentli + ' .loading-buyer-join-ajax').css('display', 'none');
            var obj = jQuery.parseJSON(msg);
            var result = obj.result;
            $(".loading-login-join").hide();
            $('.' + currentli + ' .verification_register_client').show();
            $('.' + currentli + ' #UserRegisterFormMainPage').hide(); 
            $('.' + currentli + ' #User_Id_Verify').val(result);
          });
        } else if (msg == 'invalid') {
          $('.' + currentli + ' .registeration_section_client').show();
          $('.' + currentli + ' .loading-buyer-join-ajax').css('display', 'none');
          $('.' + currentli + ' #txtMblNo').css("border-color", "#FF0000");
          $('.' + currentli + ' #error_mobile').text("* Enter Valid Mobile No.");
          $('.' + currentli + ' #error_mobile').show();
          $(".loading-login-join").css('display', 'none');
        } else {
          $('.' + currentli + ' .registeration_section_client').show();
          $('.' + currentli + ' .loading-buyer-join-ajax').css('display', 'none');
        }
      });

The code is not entering the ajax function

react native without expo how to force only light theme

React native is assembled via cli after building the apk and installing it on the device, when you switch the theme of the device, the theme of the application itself changes, which changes the text color in the textInput component to white and it turns out that white text is on a white background, the background color of some components also changes to gray , when changing the parent theme in the styles.xml file and making changes to androidManifest.xml, nothing changes, how to fix this I’m already going crazy!

Adding the line AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); in MainActivity.java also does not change the situation, also adding the line <item name="android:forceDarkAllowed">false</item> to styles.xml does not bring any changes

styles.xml:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:textColor">#000000</item>
        <item name="android:forceDarkAllowed">false</item>
        <!-- <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item> -->
    </style>
</resources>

AndroidManifest.xml:

   <resources>
       <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
           <item name="android:textColor">#000000</item>
           <item name="android:forceDarkAllowed">false</item>
           <!-- <item name="colorPrimary">@color/colorPrimary</item>
           <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
           <item name="colorAccent">@color/colorAccent</item> -->
        </style>
    </resources>

react-native 0.76
gradle: 8.0.1

Nestjs circular dependency using Jest

Inside a nestJs app using mongoose, when the app is running i don’t have any trouble.
But i want to write unit testing using jest and there is a problem in that case.

I simplify the code to focus on the problem, there is my test file:

// client.controller.spec.ts
import { Test } from '@nestjs/testing'
import { PrivateClientService } from '../client.service'
import { responseMock } from '@test/mocks/response.mock'

jest.mock('../client.service')

describe('PrivateClientController', () => {
  let privateClientService: PrivateClientService

  beforeEach(async () => {
    console.log(responseMock) // Import with alias works
    
    const moduleRef = await Test.createTestingModule({
      imports: [],
      // controllers: [],
      providers: [PrivateClientService],
    }).compile()
    jest.clearAllMocks()
  })

  describe('createClient', () => {
    it('should passed', () => {
      expect(true).toBe(true)
    })
  })
})

When i run the following test above i have this error:

src/framework/features/client/private/test/client.controller.spec.ts
  PrivateClientController
    createClient
      ✕ should passed (14 ms)

  ● PrivateClientController › createClient › should passed

    A circular dependency has been detected inside RootTestModule. Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Note that circular relationships between custom providers (e.g., factories) are not supported since functions cannot be called more than once.

      18 |     console.log(responseMock)
      19 |     
    > 20 |     const moduleRef = await Test.createTestingModule({
         |                       ^
      21 |       imports: [],
      22 |       // controllers: [PrivateClientController],
      23 |       providers: [PrivateClientService],

      at NestContainer.addProvider (node_modules/@nestjs/core/injector/container.js:146:19)
      at DependenciesScanner.insertProvider (node_modules/@nestjs/core/scanner.js:235:35)
      at node_modules/@nestjs/core/scanner.js:119:18
          at Array.forEach (<anonymous>)
      at DependenciesScanner.reflectProviders (node_modules/@nestjs/core/scanner.js:118:19)
      at DependenciesScanner.scanModulesForDependencies (node_modules/@nestjs/core/scanner.js:99:18)
      at async DependenciesScanner.scan (node_modules/@nestjs/core/scanner.js:31:9)
      at async TestingModuleBuilder.compile (node_modules/@nestjs/testing/testing-module.builder.js:70:9)
      at async Object.<anonymous> (src/framework/features/client/private/test/client.controller.spec.ts:20:23)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.778 s, estimated 1 s

If i comment the following line, the test passed.

// providers: [PrivateClientService],

So, my guess is, it’s come from PrivateClientService, but after a lot of research i don’t understand or find why.

// client.service.ts
import { Injectable, NotFoundException } from '@nestjs/common'
import { isValidObjectId } from 'mongoose'

import { InvalidObjectIdException } from '@framework/exceptions/InvalidObjectId.exception'

import { Client } from '../schemas/client.schema'
import { ClientRepository } from '../client.repository'

@Injectable()
export class PrivateClientService {
  constructor(private readonly clientRepository: ClientRepository) {}

  async createClient(client: Client): Promise<Client> {
    const newClient = await this.clientRepository.create(client)

    return newClient
  }

  async updateClient(id: string, client: Client): Promise<Client> {
    if (!isValidObjectId(id)) throw new InvalidObjectIdException()

    const updatedClient = await this.clientRepository.findByIdAndUpdate(id, client)

    if (!updatedClient) {
      throw new NotFoundException()
    }

    return updatedClient
  }

  async deleteClient(id: string): Promise<Client> {
    if (!isValidObjectId(id)) throw new InvalidObjectIdException()

    const client = await this.clientRepository.findByIdAndDelete(id)

    if (!client) {
      throw new NotFoundException()
    }

    return client
  }
}

I’m pretty new to nestjs/nodeJs, for those who wonder i follow this exact repo architecture.

At this time, i try to:

  • forwardRef the constructor in PrivateClientService
  • comment the two import for client.schema and client.repository inside
    PrivateClientService
  • I have check if the import alias works fine (yes)
  • Keep hope