Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
Unable to get state value in when using long-lived connection in react base chrome extension

I have a Popup.jsx and a Background.js. The Popup creates a long lived connection to my background service worker.

I am maintaining a state in my Popup.jsx, which looks like this

const [projectDetail, setProjectDetail] = useState({ projectCode: null })

The useEffect of my Popup.jsx looks like this,

useEffect(() => {
    port = chrome.runtime.connect({ name: 'Background Connection' })
    port.onMessage.addListener(({ action, payload }) => {

      switch (action) {
        case ACTION.SET_PROJECT_DETAIL:
          setProjectDetail(payload);
          break;
  
        case ACTION.CHECK_STATE:
          console.log(projectDetail)
          break;
   
        
        default:
          break;
      }
  
    })
    port.postMessage({ action: ACTION.GET_PROJECT_DETAIL })
    return () => {
      port.disconnect()
    }
  }, [])

As you can see, after attaching the listener for onMessage on the port variable (which is defined outside the component scope), I am sending a message to the Background.js to get project detail. The Background.js responds back with as per the following code:

chrome.runtime.onConnect.addListener(function (port) {
  // console.log("🚀 ~ file: index.js ~ line 182 ~ chrome.runtime.onConnect.addListener ~ port", port)

  port.onMessage.addListener(function ({ action, payload }) {

    if (action === ACTION.GET_PROJECT_DETAIL) {
       port.postMessage({ action: ACTION.SET_PROJECT_DETAIL, payload: { projectCode: "Some value"} })
    }

   // ...Removed more code for brevity

  });
});

Assume that I have a user interaction button which tells the Background.js to send a message to the Popup.jsx which matches the case ACTION.CHECK_STATE:, so evidently, I am expecting the Popup.jsx to console log the value {projectCode: "Some value"} as the state in the component has been updated (I have verified that it does by using ReactDevTools).

However, it prints { projectCode: null } which was the initial state value.

Note: the user interaction does not happen immediately after the component mounts, so its not that I am trying to get the state value immediately after I have set it.

I am unable to get the updated state value inside the callback function for addListener. Not sure what am I doing wrong here.

about 4 years ago · Santiago Gelvez
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda