Câu hỏi phỏng vấn React Native
Câu hỏi

What is wrong with this cod...

Câu trả lời

To answer the interview question "What is wrong with this code for querying a native API?" let's analyze the provided code snippet and identify potential issues:

fetchToken() {
  fetch('http://10.0.2.2:8163/extension/auth', {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-type': 'application/json'
    }
  })
  .then((response) => console.log('successful fetchToken response: ', response.json()))
  .catch((error) => console.log('fetchToken error: ', error))
  .done();
}

Issues in the Code

  1. Incorrect Handling of response.json():

    • The response.json() method returns a promise, but it is being logged directly without waiting for the promise to resolve. This will not log the actual JSON response but rather the promise object.
    • Fix: Chain another .then() to handle the resolved JSON data.
      fetchToken() {
        fetch('http://10.0.2.2:8163/extension/auth', {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
          }
        })
        .then((response) => response.json())
        .then((data) => console.log('successful fetchToken response: ', data))
        .catch((error) => console.log('fetchToken error: ', error))
        .done();
      }
  2. Error Handling:

    • The current error handling only logs the error to the console. While this is not necessarily wrong, it is often beneficial to provide more robust error handling, such as user notifications or retries.
    • Improvement: Implement more comprehensive error handling based on the application's requirements.
  3. Use of done():

    • The .done() method is not a standard part of the Fetch API or Promises in JavaScript. It is likely a mistake or a remnant from a different context (e.g., jQuery's Deferred objects).
    • Fix: Remove the .done() call.
      fetchToken() {
        fetch('http://10.0.2.2:8163/extension/auth', {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
          }
        })
        .then((response) => response.json())
        .then((data) => console.log('successful fetchToken response: ', data))
        .catch((error) => console.log('fetchToken error: ', error));
      }
  4. Network Configuration for Localhost:

    • When testing on a physical device or an emulator, localhost does not refer to the development machine but to the device itself. The code correctly uses http://10.0.2.2:8163/ for Android emulators, which is an alias for 127.0.0.1 on the host machine.
    • ...
expert

expert

Gợi ý câu hỏi phỏng vấn

expert

How is InteractionManager important?

senior

Differentiate ScrollView and FlatList?

entry

What are native apps?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào