Search code examples
javascriptreactjsreact-native

Twitter clone doesn't show new posts after adding new ones unless the app is restarted - React Native


I'm creating a twitter clone as a small project to get better with IOS development, everything is going smoothly besides the fact that whenever i add a post, the app won't reflect those changes unless it is restarted, I'm almost 100% sure its because the fetch call that grabs the post information isn't in the components return statement and so it isn't running on render, but when I try to put the fetch call inside of the function, it doesn't recognize the variable anymore... If anyone could tell me why this is happening it would be greatly appreciated!

import React from 'react';
import { View, Text, StyleSheet, ScrollView, FlatList } from 'react-native'

var posts = ''

fetch("API URL WAS HERE BUT ITS PRIVATE NOW")
  .then(response => response.json())
  .then(data => {
    posts = data;
    posts
  });

function Posts({ navigation , route }) {
    return(
        <View style={styles.container}>
            <FlatList
                refreshing
                inverted
                data={posts}
                renderItem={({ item }) => (
                    <View style={styles.background} key={item.postid}>
                        <View style={styles.usernameBox}>
                            <Text>@{item.username}</Text>
                        </View>
                        <Text style={{color: "white"}}>{item.content}</Text>
                    </View>
                )}
            />
        </View>
    )
}

const styles = StyleSheet.create({
    background: {
        width:370,
        minHeight: 60,
        height: "auto",
        borderRadius: 15,
        padding: 10,
        paddingBottom: 40,
        marginLeft: 30,
        marginRight: 30,
        marginBottom: 10,
        marginTop: 10,

        backgroundColor: "#656CB4"
    },
    container: {
        flex: 1
    },
    usernameBox: {
        width: 100,
        height: 25,
    }
})

export default Posts;

Solution

  • to show an example of what Chukwujiobi Canon suggests, try this:

    function Posts({navigation,route}){
        // call useState to receive a state variable (posts) and setter (setPosts) that you could name whatever you want
        const [posts, setPosts] = useState('');
        fetch('your url')
            .then(res => res.json())
            // call setter with new data
            .then(data => setPosts(data))
        return (/* your return code that uses "posts" */)
    }
    

    note: useState will not show up in an immediate call to console.log within the same scope of when you call "setPosts".

    as they explained, react will not handle "normal" variable like you would expect. if you want them to persist between renders, some form of state is your answer. if your use case requires global data, look into using something like redux. and if you find yourself passing data deeply through a bajillion components, react's useContext hook could be useful to help manage that.

    react useState docs

    react useContext docs