简体   繁体   中英

setting state on react native issue

Am trying to print out the data I get from a back end server built with nodejs on my react native app screen using axios but for some reason I get no results

here is the code i used:

my useArticle hook code:

import { useEffect, useState } from "react";
import articles from "../api/articles";
import axios from "axios";
export default () => {
  const [docs, setDocs] = useState([]);
  const [errorMessage, setErrorMessage] = useState("");
  const loadApi = async () => {
    // wait for a reponse to get back once it does with some data we asign that data to the reponse variable
    try {
      const response = await axios.get("http://localhost/articles");
      //console.log(response.data);
      setDocs(Array.from(response.data));
    } catch (err) {
      setErrorMessage("Something went wrong");
    }
  };
  // bad code
  //searchApi("pasta");
  useEffect(() => {
    loadApi();
  }, []);

  return [loadApi, docs, errorMessage];
};

// we extracted the resutls logic into this helper function we then imported
// to the main screen in order to use SearchApi , results , errorMessage
// now this helper function can be used inside other components

and here the screen that supposed to show the results:

import React, { useState } from "react";
import { View, Text, StyleSheet, ScrollView, FlatList } from "react-native";
import SearchBar from "../components/SearchBar";
import useResults from "../hooks/useResults";
import ResutlsList from "../components/ResultsList";
import ResutlsListVer from "../components/ResultsListVer";
import useArticles from "../hooks/useArticles";
const TrackCreateScreen = () => {
  const [loadApi, docs, errorMessage] = useArticles();

  /*****************************FUNCTION TO FILTER OUT RESULTS SHOWING USING THE PRICE *************************/

  /*******************************WE WONT NEED THIS UP NOT DOWN************************************* */
  /******************************** REMOVE VIEW AND REPLACE IT WITH <> SO WE DONT HAVE TO WORRY ABOUT ADDING FLEX **********************************************/
  return (
    <View>
      {docs.map((article, index) => (
        <Text key={index}>{article.title}</Text>
      ))}
      <Text style={styles.Text}>{docs.length}</Text>

      <FlatList
        data={docs}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <View style={{ backgroundColor: "#abc123", padding: 10, margin: 10 }}>
            <Text style={{ color: "#fff", fontWeight: "bold" }}>
              {item.title}
            </Text>
            <Text style={{ color: "#fff" }}>{item.excerpt}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    //flex: 1, // when ever we have a content that is being cut off or expanding off the screen
  },
  Text: {
    fontSize: 32,
    alignItems: "center",
  },
});
export default TrackCreateScreen;

I did some console. logs and for some reason the docs in useState is just an empty array, even though when I used console.log (response. data) I got all the results shown on my console.

Am also trying to filter out the null values from my API and just show the ones with actual value so if anyone could point out to me how I will be able to do that it will be much appreciated.

here is a sample of data i get when i used console.log(response.data):

Object {
  "data": Array [
    Object {
      "_id": "5eb95a068d162448a4e6a9c2",
      "excerpt": "The shooting of Ahmaud Arbery.",
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c3",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c4",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c5",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },

The problem may be in the Array.from method since from console it can be seen you are already getting array so need to convert it further

Instead of this

setDocs(Array.from(response.data));

try

 setDocs(response.data.data);

If you have used setState function, then there might be an issue with setDoc() as it takes time to set your data, since setState is an async function.

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