Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
How to re-render React Component when outside function call

I created a class object that stores the postlist. When the post was updated, the Pub-Sub pattern subscription function was registered.

class PostLoad extends PubSub { 
  store = [];
  constructor (){
    super();
    this.connectSocket = connectSocket(this.projectUid, async (type, post) => {
      console.log('Socket HOOK', type, post);
      if (type === 'insert') await this.newPostPush(post);
      if (type === 'update') {
        const {deleted} = post;
        if (deleted) await this.deletePostInStore(post.id);
      }
    });
  }
  async postLoad () {
   // ...API LOAD
   const value = axios.get('');
   this.store = value;
  }
  private async newPostPush(post: HashsnapPostItem) {
    if (post.type === 'video') return;
    const storeItem = {...post, img: await loadImage(post.url)} as HashsnapPost;
    this.store.unshift(storeItem);
    if (this.store.length > this.limit) this.store.splice(this.limit);
    this.emit('insert', {post: storeItem, store: this.store});
  }
  private deletePostInStore(targetId: number) {
    this.store.push(...this.store.splice(0).filter(({id}) => id !== targetId));
    this.emit('delete', {postId: targetId, store: this.store});
  }
}

React component executes events registered in Pub-Sub, When the post was updated, the status value was changed, but there was no change.

const PostList = () => {
  const [postList, setPostList] = useState([]);
  const postLoad = store.get('postLoad'); // PostLoad Class Object

  useEffect(() => {
   setPostList(postLoad.store);
  }, []);

  postLoad.on('delete', (payload) => {
    setPostList(postLoad.store);
  })

  postLoad.on('insert', (payload) => {
    setPostList(postLoad.store);
  })

  return <div>
   {postList.map((post, i) => {
     return <div key={`post-${i}`}></div>
   })}
  </div>
}

What I want is that when the Pus-Sub event is executed, the status value changes and re-rends.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

   async postLoad () {
       // ...API LOAD- axios is a async func, need await this
       const value = await axios.get('');
       this.store = value;
      }

    postLoad.on('delete', (payload) => {
        setPostList(postLoad.store);
    })

    postLoad.on('insert', (payload) => {
        setPostList(postLoad.store);
    })

    // thest two register on postLoad will repeat many times, just use hook useEffect, if postLoad always change, useRef, so the right code is below

const PostList = () => {
  const [postList, setPostList] = useState([]);
  const {current: postLoad} = useRef(store.get('postLoad'));

  useEffect(() => {
      setPostList(postLoad.store);
      postLoad.on('delete', (payload) => {
        setPostList(postLoad.store);
      })
      postLoad.on('insert', (payload) => {
        setPostList(postLoad.store);
      })
      return () => {
        // please unregister delete and insert here
      }
  }, [postLoad]);

  return <div>
   {postList.map((post, i) => {
     return <div key={`post-${i}`}></div>
   })}
  </div>
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda