Jak ponownie wyświetlić niestandardowe hook po początkowym renderowania

0

Pytanie

Mam własny hak z nazwą useIsUserSubscribed to sprawdzić, podpisany czy dany użytkownik. Zwraca wartość true, jeśli użytkownik jest zarejestrowany, a wartość false, jeśli użytkownik nie podpisana...

import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { checkSubscription } from "../services";

// this hook checks if the current user is subscribed to a particular user(publisherId)
function useIsUserSubscribed(publisherId) {
  const [userIsSubscribed, setUserIsSubscribed] = useState(null);
  const currentUserId = useSelector((state) => state.auth.user?.id);

  useEffect(() => {
    if (!currentUserId || !publisherId) return;

    async function fetchCheckSubscriptionData() {
      try {
        const res = await checkSubscription(publisherId);
        setUserIsSubscribed(true);
      } catch (err) {
        setUserIsSubscribed(false);
      }
    }

    fetchCheckSubscriptionData();
  }, [publisherId, currentUserId]);

  return userIsSubscribed;
}

export default useIsUserSubscribed;

...U mnie jest przycisk, wykorzystująca ten haczyk, który wyświetla tekst w zawieszeniu na podstawie logicznego wartości zwróconego z useIsUserSubscribed...

import React, { useEffect, useState } from "react";
import { add, remove } from "../../services";
import useIsUserSubscribed from "../../hooks/useIsUserSubscribed";

const SubscribeUnsubscribeBtn = ({profilePageUserId}) => {

  const userIsSubscribed = useIsUserSubscribed(profilePageUserId);
  
  const onClick = async () => {
    if (userIsSubscribed) {
       // this is an API Call to the backend
      await removeSubscription(profilePageUserId);

    } else {
      // this is an API Call to the backend
      await addSubscription(profilePageUserId);
    }
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
  }

  return (
    <button type="button" className="sub-edit-unsub-btn bsc-button" onClick={onClick}>
          {userIsSubscribed ? 'Subscribed' : 'Unsubscribed'}
    </button>
  );
} 

Po onClick Chciałbym ponownie wysłać swój useIsUserSubscribed następnie należy założyć tak, aby tekst mojej przycisku przełączać. Czy można to zrobić?

3

Najlepsza odpowiedź

2

nie można używać efekt użycia w swoim haku do tego celu, spróbuj tego :

hak :

function useIsUserSubscribed() {
  const currentUserId = useSelector((state) => state.auth.user?.id);


  const checkUser = useCallback(async (publisherId, setUserIsSubscribed) => {
    if (!currentUserId || !publisherId) return;
      try {
        const res = await checkSubscription(publisherId);
        setUserIsSubscribed(true);
      } catch (err) {
        setUserIsSubscribed(false);
      }
    
  }, [currentUserId]);

  return {checkUser};
}

export default useIsUserSubscribed;

składnik :

const SubscribeUnsubscribeBtn = ({profilePageUserId}) => {
    const [userIsSubscribed,setUserIsSubscribed]=useState(false);
    const { checkUser } = useIsUserSubscribed();

     useEffect(()=>{
        checkUser(profilePageUserId,setUserIsSubscribed)
     },[checkUser,profilePageUserId]);
  
  const onClick = async () => {
    if (userIsSubscribed) {
       // this is an API Call to the backend
      await removeSubscription(profilePageUserId);

    } else {
      // this is an API Call to the backend
      await addSubscription(profilePageUserId);
    }
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
    checkUser(profilePageUserId,setUserIsSubscribed)
  }

  return (
    <button type="button" className="sub-edit-unsub-btn bsc-button" onClick={onClick}>
          {userIsSubscribed ? 'Subscribed' : 'Unsubscribed'}
    </button>
  );
} 

można także dodać kilka stanu pobrania na swój haczyk i zwrócić je też, aby sprawdzić, zakończony, czy proces już czy nie

2021-11-24 03:03:13

Zamierzam ponownie skorzystać z tej logiki w innych częściach aplikacji. Jaki jest najlepszy sposób, aby to zrobić kilka statku, gdy hak nie jest najlepszym podejście?
Simone Anthony

@SimoneAnthony nie ma nic złego w haku, i można ich używać, ale zauważyłem również, że używasz redux, więc można również wykorzystać działania redux-thunk
Mohammad
2

Dodaj opcję w zależności od efektu użycia, podpisanego przez użytkowników.

hak :

function useIsUserSubscribed(publisherId) {
    const [userIsSubscribed, setUserIsSubscribed] = useState(null);
    const currentUserId = useSelector((state) => state.auth.user?.id);
    // add refresh dependece
    const refresh = useSelector((state) => state.auth.refresh);

    useEffect(() => {
        ...
    }, [publisherId, currentUserId, refresh]);
    ...
}

składnik :

const onClick = async () => {
    ...
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
    // when click, you can dispatch a refresh flag.
    dispatch(refreshSubState([]))
}

Ono przymusowej weryfikacji metody.

hak :

function useIsUserSubscribed(publisherId) {
    const [update, setUpdate] = useState({});
    const forceUpdate = () => {
        setUpdate({});
    }  

    return {userIsSubscribed, forceUpdate};
}

składnik :

const {userIsSubscribed, forceUpdate} = useIsUserSubscribed(profilePageUserId);

const onClick = async () => {
    ...
    forceUpdate();
}
2021-11-24 02:56:11
0

Oto jeszcze jedno rozwiązanie użytkownika @bitspook

SubscribeUnsubscribeBtn ma zależność od useIsUserSubscribedale useIsUserSubscribed nie zależy ani od czego z SubscribeUnsubscribeBtn. Zamiast tego, useIsUserSubscribed zapisuje stan lokalny. Masz kilka opcji tutaj:

  1. Przesuń stan dotyczącą tego, podpisany czy użytkownik jest zalogowany, czy nie, na jeden poziom wyżej, tak jak używasz Redux, być może, w Redux.
  2. Komunikuj się z useIsUserSubscribed co trzeba zmienić jego stan wewnętrzny.

Dla 1)

  const [userIsSubscribed, setUserIsSubscribed] = useState(null);

przenieś to stan w magazynie Redux i używać go za pomocą useSelector.

Dla 2)zwraca tablicę wartości i oddzwanianie z haka, a nie tylko wartość. To pozwoli ci komunikować się z komponentu z powrotem w hak.

W useIsUserSubscribed,

  return [userIsSubscribed, setUserIsSubscribed];

Następnie w onClickmożna zadzwonić setUserIsSubscribed(false)zmiana stanu wewnętrznego haka i ponowne wizualizacja danego składnika.

2021-11-24 03:37:35

W innych językach

Ta strona jest w innych językach

Русский
..................................................................................................................
Italiano
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................