Django & React-Native: RN component connection with Django

Shawnpy·2021년 9월 22일
0

Django & React-Native

목록 보기
5/14

Let's assume that you know basics of React Native and Django. In this chapter, I will talk about how to connect React Native to Django backend. Especially, how to send data to the backend, and use response with "fetch".

How does React Native interact with Django?

We can understand fetch as "request". Once we fetch certain url from the React Native mobile, Django backend will take this fetch as request, and compute the function. As the server returns the response, RN will receive the response right after.

This chapter will discuss about the basic fetch structure in React Native with GET request. If you wonder how to build Django structure, or POST request structure from RN, please refer to the next chapters.

GET fetch structure at RN

const [data, setData] = useState();

useEffect(() => {
    fetch('http://127.0.0.0:8000/main/', { method: 'GET' })
      .then(response => {
        if (response.status != '200') {
          setResponseErrorText('Sorry,\nCurrently, there is something wrong.');
        } else {
          setResponseErrorText();
          return response.json()
        }
      })
      .then(responseJson => {
        if (responseJson) {
          setData(responseJson);
        }
      })
      .catch(error => setResponseErrorText('error: ' + error));
  }, [])
  
  <View>
      <Text>{data}</Text>
  </View>

This is the basic structure of GET request at RN screen. Let's cut it down.

why "useEffect"?

=> As soon as the user enters the screen, the fetch() function will initiate if there is no useEffect() function. If you do not use useEffect(), it will occur error as well, because the function will not be able to escape.

how to use fetch()?

  • Put the request address at the first parameter, and put other options at the second one as dictionary. Make sure you finish the address with / at the end. you can use .then() to handle response as a function.

  • At the first .then(), you can check the response status first to sort how to show the screen for the user. if the status is 200, you can return the response data as json format.

  • At the second .then(), if there was a return with status 200, you can set the state with json formatted response(reponseJson) by useState().

  • If there was an error, .catch() will find the error as variable, and you can use the variable. I personally saved the error variable at the reponseErrorText state. Feel free to handle the error!

profile
Do what you feel now

0개의 댓글