React using Async Context for SocketIO

Viewed 289

I am trying to establish a socket connection with authentication. The token is in the SecureStore Expo, so I have to use an Async method. I was advised to use Context to give all my components access to the socket.

const DrawerNavigation = () => {
  const [socket, setSocket] = useState();

  useEffect(() => {
    async function connectToSocket() {
      const token = await SecureStore.getItemAsync('ACCESS_TOKEN');
      setSocket(io('http://10.0.2.2:3000', {
        extraHeaders: {
          'authorization': `Bearer ${token}`
        }
      }));
    }
    connectToSocket();
  }, [])


  return (
    <SocketContext.Provider value={socket}>
      <Drawer.Navigator>
           .........
      </Drawer.Navigator>
    </SocketContext.Provider>
  );
};

Then, I wrote my component Home

const Home = ({ navigation }) => {
  const socket = useContext(SocketContext);

  useEffect(() => {
    // Anything in here is fired on component mount.
   if (socket) {
    socket.on('connect', () => {
      console.log('connected');
    });
   }
  }, [])

The socket connection with the server is not established. I guess useEffect is not called again when socket changes.

Thanks for helping

1 Answers

Thanks to @Tracer69 answers, it works now! I answer to my question with the missing part for those who are curious.

  useEffect(() => {
    // Anything in here is fired on component mount.
    if (socket) {
      socket.on('connect', () => {
        console.log('connected');
        getLocation();
      });
    }
    return () => {
      // Anything in here is fired on component unmount.
      if (socket) {
        socket.disconnect();
      }
    }
  }, [socket])
Related