Sometimes, we want to make a GET request with query string with Fetch in React Native
In this article, we’ll look at how to make a GET request with query string with Fetch in React Native
How to make a GET request with query string with Fetch in React Native?
To make a GET request with query string with Fetch in React Native, we call encodeURIComponent
on each query parameter value.
For instance, we write:
import * as React from 'react';
import { View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
export default function App() {
const getReq = async () => {
const data = { foo: 1, bar: 2 };
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/?foo=${encodeURIComponent(
data.foo
)}&bar=${encodeURIComponent(data.bar)}`,
{
method: 'GET',
}
);
console.log(await res.json());
};
React.useEffect(() => {
getReq();
}, []);
return <View></View>;
}
to call fetch
with a URL with the foo
and bar
query parameters.
We set each query parameter value to a string that has been encoded with encodeURIComponent
We set the method
to 'GET'
to make a GET request.
Conclusion
To make a GET request with query string with Fetch in React Native, we call encodeURIComponent
on each query parameter value.