Skip to content

read() returns number instead of Uint8Array #22

Open

Description

@2ico

I am trying to read() a text/event-stream. The backend already works in curl and in a Next.js app.

value returned from reader.read() is a number instead of a Uint8Array, which means the Typescript types are broken.

const fetchMessage = async() => await fetch("http://192.168.1.27:3000/api/chat", {
    "credentials": "include",
    "headers": {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "text/plain;charset=UTF-8",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache"
    },
    "body": "{}",
    "method": "POST",
    "mode": "cors"
});

  useEffect(() => {

    function createChunkDecoder() {
      const decoder = new TextDecoder();
        return function(chunk: Uint8Array) {
          console.log(typeof chunk)
          if (!chunk)
            return "";
          return decoder.decode(chunk, { stream: true });
        };
    }

    fetchMessage()
      .then(response => response.body)
      .then(async (stream) => {
        if(!stream){
          return
        }
        const reader = stream.getReader();      
        const decode = createChunkDecoder();

        let streamedResponse = ''

        while(true) {

          const { done, value } = await reader.read();
          if (done) {
            break;
          }

          streamedResponse += decode(value);
          console.log(streamedResponse)

        }
      })
    },[])
   

Activity

  1. 2ico commented on Dec 14, 2023

    @2ico
    Author

    I figured out that I need to set the option "reactNative": { textStreaming: true }.
    Now the type is correct, but I receive a single chunk for the entire contents of the response.

  2. 2ico commented on Dec 15, 2023

    @2ico
    Author

    I tried on iPhone and it works. Seems to be a problem with Android only.
    Related: https://stackoverflow.com/questions/69235694/react-native-cant-connect-to-sse-in-android/69235695#69235695

  3. fukemy commented on Feb 22, 2024

    @fukemy

    Hi, did you make it work for Android?

  4. 2ico commented on Feb 27, 2024

    @2ico
    Author

    Hi, no I didn't. Debug mode doesn't stream.
    I read that it works fine in release mode, but I couldn't try it yet.

  5. reopened this on Feb 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions