简体   繁体   中英

Get response.data from fetch() as variable to use in React-Native

I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.

const getFlights = async () => {
  const token = await getAsyncData("token");
  instance({
    method: "get",
    url: "/api/flights/",
    headers: {
      Authorization: `Token ${token}`,
    },
  })
    .then(function (response) {
      // console.log(response.data.results); // shows an array of JSON objects
      return response.data.results; // I've also tried response.data.results.json()
    })```

I just want the response returned as a variable that I can use to populate a FlatList component in RN.

const FlightListScreen = () => {
  const [list, setList] = useState([]);
  const flights = getFlights(); // currently returns as a promise object

Thank you for your help.

I think you have to store the response object directly to the json method. And then with that response you can store it to the variable

.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
 })

you are sending token without a bearer. Concrete your token with bearer like this

     headers: {
        Authorization: "Bearer " + token,
      },

and another thing is your response class are not right this should be like this

.then((response) => response.json())
.then((responseJson) => {
    API will Resopne here....
                        }

this is a complete example to call API with Token

 fetch("/api/flights/", {
      method: "GET",
      headers: {
        Authorization: "Bearer " + token,
      },
    })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
          setState(responseJson.VAlue);
      })
      .catch((error) => {
        alert(error);
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM