0

I have this React Native code and I'd like to call the function getPosts before rendering the screen. How do I do this?

import React, {useState} from 'react';
import {FlatList, StyleSheet, SafeAreaView} from 'react-native';
import PostGoalCard from '../components/PostGoalCard';
import Loader from '../components/Loader';
import axios from 'axios';

const PostsScreen = ({navigation}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = React.useState([])
  const url = 'http://10.0.2.2:8000';

  const getPosts = () => {
    axios
      .get(`${url}/posts`)
      .then(response => {
        console.log(response)
        setData(response.data);
      })
      .catch(error => {
        console.log(JSON.stringify(error));
      });
  } 

  return (
    <SafeAreaView style={styles.container}>
      <Loader loading={loading} />
      <FlatList
        style={styles.flatlist}
        data={data}
        keyExtractor={(item, index) => index}
        renderItem={({item}) => (
          <PostGoalCard key={item.username} item={item} navigation={navigation} />
        )}
      />
    </SafeAreaView>
  );
};

export default PostsScreen;

1 Answer 1

1

You can try this

import React, {useState, useEffect} from 'react';
import {FlatList, StyleSheet, SafeAreaView} from 'react-native';
import PostGoalCard from '../components/PostGoalCard';
import Loader from '../components/Loader';
import axios from 'axios';

const PostsScreen = ({navigation}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = React.useState([])
  const url = 'http://10.0.2.2:8000';

  useEffect(() => {
        getPosts();
    }, []);


  const getPosts = () => {
    axios
      .get(`${url}/posts`)
      .then(response => {
        console.log(response)
        setData(response.data);
      })
      .catch(error => {
        console.log(JSON.stringify(error));
      });
  } 

  return (
    <SafeAreaView style={styles.container}>
      <Loader loading={loading} />
      <FlatList
        style={styles.flatlist}
        data={data}
        keyExtractor={(item, index) => index}
        renderItem={({item}) => (
          <PostGoalCard key={item.username} item={item} navigation={navigation} />
        )}
      />
    </SafeAreaView>
  );
};

export default PostsScreen;

useEffect will render getPosts before rendering the screen.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.