Come re-rendering personalizzato gancio [duplica]

0

Domanda

Ho personalizzato il gancio di nome useIsUserSubscribed che controlla uno specifico utente è iscritto. Restituisce true se l'utente è iscritto e false se l'utente non è iscritto...

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;

...Ho un pulsante con questo gancio che rende il testo in modo condizionale in base boolean restituiti da 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>
  );
} 

Dopo onClick Vorrei eseguire il rendering di mio la useIsUserSubscribed il gancio in Modo che il mio testo del pulsante cambia. Questo può essere fatto? Devo usare un approccio diverso?

javascript react-hooks reactjs
2021-11-24 03:45:44
1

Migliore risposta

1

SubscribeUnsubscribeBtn ha una dipendenza useIsUserSubscribedma useIsUserSubscribed non dipende da nulla da SubscribeUnsubscribeBtn. Invece, useIsUserSubscribed è talmente semplice mantenere aggiornati i locali dello stato. Avete un paio di scelte:

  1. Spostare lo stato riguardo whetehr utente sia iscritto o meno ad un livello superiore, dal momento che si sta utilizzando Redux, forse in Redux.
  2. Comunicare per useIsUserSubscribed che avete bisogno di cambiare il suo stato interno.

Per 1)

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

spostare questo stato di Redux conservare e utilizzare con useSelector.

Per 2), restituisce un array di valore e richiamata dal gancio, al posto del valore. Essa vi permetterà di comunicare componente indietro nel gancio.

In useIsUserSubscribed,

  return [userIsSubscribed, setUserIsSubscribed];

Quindi in onClickè possibile chiamare setUserIsSubscribed(false), cambiare il gancio stato interno e re-rendering componente.

2021-11-24 03:58:26

Dal momento che questo è stato contrassegnato come un duplicato, ti dispiace mettere le vostre risposte qui? stackoverflow.com/questions/70090096/... sarà aiutare un sacco di persone. Farò in modo di darvi un upvote.
Simone Anthony

Sembra che tu lo abbia postato la risposta nell'altra domanda. Quindi suppongo che mi limiterò a lasciare questo qui.
bitspook

In altre lingue

Questa pagina è in altre lingue

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