'Reload screen after action - REACT NATIVE

I want to have a screen which contains all my favorite subjects. I have to select these from another screen, with all the subjects. The functionallity behind it works fine, but the problem I'm having right now, is that when a subject is chosen as a favorite, it doesn't show up on the favorite screen... Only after a forced reload... Any ideas how I can fix this?

import {
    Button,
    Text,
    View,
    StyleSheet,
    FlatList,
    SafeAreaView,
    StatusBar,
    ScrollView,
} from "react-native";
import React, {Component, useContext, useState} from "react";
import Ionicons from 'react-native-vector-icons/Ionicons';
import {TouchableOpacity} from "react-native";

import getAccessToken from "../functions/getAccessToken";
import refreshToken from "../functions/refreshToken";

import Subject from "../functions/SubjectLoaders/Subject";
import styleSubjectList from "../styles/styleSubjectList";
import backendURL from "../backendURL";
import getFromStore from "../functions/getFromStore";

import {BottomTabBarHeightContext, useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import FavoriteSubject from "../functions/SubjectLoaders/FavoriteSubject";
import {AuthContext} from "../Authentication/AuthProvider";


function  SubjectListScreen({navigation}) {
    const [subjects, setSubjects] = useState([]);
    const [details, setDetails] = useState([]);
    const [hasLoaded, setHasloaded] = useState(false);
    const tabBarHeight = useBottomTabBarHeight();

    React.useEffect(()=> {
        const constructor = async () => {
            await refreshToken();
            let token = await getAccessToken();
            let ownId = await getFromStore("ownId")
            console.log("ownId: " + ownId)
            let axios = require('axios');

            let config = {
                method: 'get',
                url: backendURL + '/subjectManagement/subjects',
                headers: {
                    'Authorization': 'Bearer ' + JSON.parse(token)
                }
            };
            axios(config)
                .then(function (res) {
                    // console.log(res.data)
                    setSubjects(res.data);
                    setHasloaded(true);
                    //console.log(res.data);
                }).catch(function (error) {
            });
        }
        constructor();
    },[])


    // if(!hasLoaded) return null;

    return(
        <View style={styleSubjectList.container}>
            <SafeAreaView style={{justifyContent: 'center',}}>
                <FlatList
                    data={subjects}
                    renderItem={ ({item}) => {
                        return <FavoriteSubject subject={item}/>
                    }}
                    keyExtractor={ subject => subject.id }
                />
            </SafeAreaView>
        </View>
    )
}

export default SubjectListScreen;

This is the page that should reload!

import React, {useContext, useState} from "react";
import { Pressable } from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import styleSubjectList from "../../../styles/styleSubjectList";
import refreshToken from "../../refreshToken";
import getAccessToken from "../../getAccessToken";
import getFromStore from "../../getFromStore";
import addToFavorites from "./addToFavorites";
import removeFromFavorites from "./removeFromFavorites";
import backendURL from "../../../backendURL";
import axios from "axios";
import removeFirstAndLast from "../../removeFirstAndLast";
import {AuthContext} from "../../../Authentication/AuthProvider";
import isRole from "../isRole";

const Hart = ({subject}) => {
    const { userInfo } = useContext(AuthContext);
    const [liked, setLiked] = useState(false);
    const [hasloaded,setHasloaded] = useState(false);
    const [ownId, setOwnId] = useState('');
    const [token, setToken] = useState('');
    const [favourite, setFavourite] = useState([]);
    const favouriteId = [];

    React.useEffect(()=> {
        const constructor = async () => {
            await refreshToken();

            let token = await getAccessToken();
            setToken(token);
            let id = await getFromStore("ownId");
            id = removeFirstAndLast(id)
            setOwnId(id)

            const axios = require('axios');
            const config = {
                method: 'get',
                url: backendURL + '/userManagement/users/' + id,
                headers: {
                    'Authorization': 'Bearer ' + JSON.parse(token)
                }
            };

            axios(config)
                .then(function (response) {
                    // setFavourite(response.data.favouriteSubjects)
                    for(let i = 0; i<response.data.favouriteSubjects.length; i++) {
                        if(response.data.favouriteSubjects[i].id === subject.id) setLiked(true)
                    }
                })
        }
        constructor().then(() => {
            setHasloaded(true);
        }).catch(e=>console.log(e));
    },[])


    const checkFavorite = () => {
        setLiked((isLiked) => !isLiked)
        if(liked) {
            console.log("verwijderen uit favorieten");
            removeFromFavorites(subject,ownId, token);
        }
        else {
            console.log("toevoegen aan favorieten");
            addToFavorites(subject,ownId,token);
        }
    }
    // console.log(favourite)
    if(!hasloaded || isRole("ROLE_COORDINATOR",userInfo) || isRole("ROLE_PROMOTOR",userInfo) || isRole("ROLE_CONTACT",userInfo) || isRole("ROLE_ADMIN",userInfo)) return null;
    else{
        return (
            <Pressable style={styleSubjectList.heartIcon} onPress={ () => checkFavorite()}>
                <MaterialCommunityIcons
                    name={liked ? "heart" : "heart-outline"}
                    size={20}s
                    color={liked ? "red" : "white"}
                />
            </Pressable>
        );
    }
};

export default Hart;

The function addToFavorites/removeFromFavorites should trigger the change...

import removeFirstAndLast from "../../removeFirstAndLast";
import backendURL from "../../../backendURL";

const removeFromFavorites = async (subject,ownId,token) => {
    let axios = require('axios');
    let qs = require('qs');
    let data = qs.stringify({
        'userId': ownId,
        'subjectId': subject.id,
    });
    console.log(data)
    let config = {
        method: 'delete',
        url: backendURL + '/userManagement/users/student/favouriteSubject',
        headers: {
            'Authorization': 'Bearer ' + JSON.parse(token),
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data : data
    };
    axios(config)
        // .then(function (response) {
        //     console.log(JSON.stringify(response.data));
        // })
        .catch(function (error) {
            console.log(error);
        });
}

export default removeFromFavorites;


Solution 1:[1]

use key={Date.now()} on the component your wanted to be changed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abbbel