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

210
Visualizações
Use contexto para compartir contenido después de la conexión de socket en React

Tengo una conexión de socket a un componente, pero sus datos se usan en varios otros componentes. Para reducir la complejidad, trato de usar contextAPI para compartir contenido entre todos los demás componentes.

Aquí está mi código de conexión de socket:

 var NotificationData=""; useEffect(() => { if(!state.id){ return } var token = ((localStorage.getItem("provider__token"))? localStorage.getItem("provider__token"): sessionStorage.getItem("provider__token")) || '' let io=new WebSocket( process.env.REACT_APP_BACKEND_DEVELOPMENT_URL_SOCKET +'ws/provider_notifications/' +state.id+ '/' ); io.onopen = (e) => { io.send(JSON.stringify({'token':token})) } io.onmessage = (e) => { let data=JSON.parse(e.data); NotificationData=React.createContext(data); if(data.type && data.type === 'notification'){ setStatus(true); setTotalNotification(data.notifications_unread) } }; })

Pero de esta manera no puedo exportar mi contexto. Revisé un ejemplo que tiene la siguiente sintaxis:

 export const UserContext = React.createContext(userContextTemplate)

Pero este ejemplo solo funciona con datos estáticos.

¿Qué puedo hacer para que estos datos de contexto estén disponibles en otro componente?

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

0

Crear archivo context.js

 import { createContext, useContext, useState } from 'react' //create a context const NotificationData = createContext({}) export default NotificationData //create a provider of that context that will provide values //which can be used by all the children conponents export const NotificationDataProvider = ({ children }) => { const [notificationData, setNotificationData] = useState(null) return ( <NotificationData.Provider value={{ notificationData, setNotificationData }}> {children} </NotificationData.Provider> ) } //create a helper custom hook to used by other components who //wish to use the context values export const useNotificationDataContext = () => { const { notificationData, setNotificationData } = useContext(NotificationData) return { notificationData, setNotificationData } }

Su archivo Socket donde se establecerán los datos

 ... //get the context value which will set the notification data const { setNotificationData } = useNotificationDataContext() useEffect(() => { if (!state.id) { return; } var token = (localStorage.getItem("provider__token") ? localStorage.getItem("provider__token") : sessionStorage.getItem("provider__token")) || ""; let io = new WebSocket( process.env.REACT_APP_BACKEND_DEVELOPMENT_URL_SOCKET + "ws/provider_notifications/" + state.id + "/" ); io.onopen = (e) => { io.send(JSON.stringify({ token: token })); }; io.onmessage = (e) => { let data = JSON.parse(e.data); //After getting the data set it using the setNotificationData. //This will set the state in the provider and will re-render all //the child components using the notification data, this way all //the components using the notification data will get the updated data setNotificationData(data); if (data.type && data.type === "notification") { setStatus(true); setTotalNotification(data.notifications_unread); } }; }); ...

Su archivo index.js

 ... // Wrap your app with Notification Provider <NotificationDataProvider> <App /> </NotificationDataProvider> ...

En algún lugar de los componentes cdild donde desea utilizar los datos de notificación

 const SomeOtherComponentWhereDataIsUsed = () => { //use the notification data in this component but beware untill it //is set in that useEffect of the above component it will be an undefined value const { notificationData } = useNotificationDataContext() //use this notificationData ... }

Referencias:

https://dmitripavlutin.com/react-context-and-usecontext/

https://reactjs.org/docs/context.html

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