Gracie williams
Gracie williams

Reputation: 1145

Load component after api is fetched

I am fetching json from API and then I want to display the component

 const [jsonCat, setjsonCat] = useState([]);
  
 useEffect(() => {
    refreshCat();
  }, []);
    
 const refreshCat = async () => {
        try {
          console.log("refreshing categories");
          setjsonCat([]);
    
          getCat().then((response) => {
            setjsonCat(response);
          });
        } catch (e) {
          console.log(e);
        }
      };
    
 const CarousalLoop = (props) => {
            const BANNER_Hs = 1;
        
            if (jsonCat.length == 0) {
              return <View></View>;
            }
         
            const listItemstest = jsonCat.map((link) => {
              console.log(link.name);
              <View>
                <Text style={{ color: "red" }}>{link.name}</Text>
              </View>;
            });
            return (
              <View style={{ height: 220, backgroundColor: "brown" }}>
                {listItemstest}
              </View>
            );
          };

And Finally my render component has

{jsonCat.length ? <CarousalLoop /> : <ActivityIndicator />}

When I run this code , Activity indicator is shown until API request is fetched and then json is also received properly , console.log(link.name) is printing the names correctly but CarousalLoop is displayed without any listitems (just brown view component is shown) .

Upvotes: 0

Views: 422

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9769

Either you use return keyword

const listItemstest = jsonCat.map((link) => {
         console.log(link.name);
         return(
               <View>
                <Text style={{ color: "red" }}>{link.name}</Text>
               </View>
              )
            });

Or wrap in parenthesis

      const listItemstest = jsonCat.map((link) => (
              <View>
                <Text style={{ color: "red" }}>{link.name}</Text>
              </View>;
            ));

Upvotes: 1

ravvis
ravvis

Reputation: 147

You need to return the list of items to render from listItemstest, like this.

const listItemstest = jsonCat.map((link) => {
              console.log(link.name);
              return <View>
                <Text style={{ color: "red" }}>{link.name}</Text>
              </View>;
            });

Upvotes: 1

Related Questions