React-native fetch make javascript blocking
Asked Answered
D

0

6

Everytime i use fetch with async await it's blocking the js thread and it's frame drop to 1. here is my code:

export const apiCall = async (method, url, body) => {
    const token = await getLocalToken();
    const params = {
        method: method.toUpperCase(),
        headers: {
            Accept: 'application/json',
           'Content-Type': 'application/json'
        }
    };
    if (body) {
        params.body = JSON.stringify(body);
    }
    if (token) {
        params.headers.Authorization = `Bearer ${token}`;
    } 
    const start = Moment();
    const res = await fetch(`${apiUrl}${url}`, params);
    let json = res;     
    try {
        json = await res.json();
    } catch (e) {
        console.tron.log(e);
    }

    return json;
}
Dysphemism answered 19/2, 2018 at 5:16 Comment(13)
How do you know the JS thread is blocking? If it is, it shouldn't be due to await. JSON.stringify is a CPU-bound operation, so if the JSON is huge, could be due to that.Jodhpur
i know that because everytime i apiCall the UI is freeze and only work after the apiCall is done. i use reactotron and perf monitor to see where is the problem and find that one aboveCreel
What does getLocalToken do?Jodhpur
just a async local storage to get a short token stringCreel
i try this example of react-native and it's blocking too: facebook.github.io/react-native/docs/network.html.Creel
I don't see anything wrong with the code. Is there some sort of weird polyfill for fetch that makes it synchronous, or some babel transform doing this?Jodhpur
no. i didn't use any polyfill for fetch. it really weird. when i apiCall the JS frame rate is 60 and stop to watting the apiCall is done and then right after this it drop to 1 and then back to 60.Creel
Perhaps Reactotron is interfering? Are you using its networking plugin?Jodhpur
no. it's not reactotron. i push the app to play store and apple app store. and the problem is still existCreel
i use redux-saga i wonder if sagas is blocking the thread when i do like this: yield call(apiCall, params);Creel
Unless you're doing something CPU-blocking in your saga (like a wait loop), it shouldn't. Maybe you should add the saga to the post.Jodhpur
In my situation, the bug disappeared when exiting debug mode.Benefaction
@BùiKhôi any improvements on this? I have similar problem right now.Sarco

© 2022 - 2024 — McMap. All rights reserved.