Django & React-Native: RN component connection with Django
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!
Author And Source
이 문제에 관하여(Django & React-Native: RN component connection with Django), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@pss2138/Django-React-Native-4.-RN-component-connection-with-Django저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)