0

Using React Native Async Storage. I have a single storage item "favorites" which holds an array of post IDs. Works great, adding and removing articles successfully, but there is a problem:

In "Favorites" TabScreen - showing all currently favorited posts - it works but is rendering an outdated list of items.

E.g. Load the app (Expo), the Favorites screen shows current list, but if I go ahead and a remove an item from the array, and go back to the Favorites screen, it still shows the removed item. Same if I add a new item and navigate back to Favorite screen, new item missing.

It only updates if I reload the app.

If you don't mind taking a look, here's the relevant code:

const POSTS_QUERY = gql`
  query posts {
    posts {
        data {
            id
            attributes {
                title
            }
        }
    }
}
`

export default ({ navigation }) => {

const [isLoading, setIsLoading] = useState(true)
const [isAsyncLoading, setIsAsyncLoading] = useState(true)
const [nodes, setNodes] = useState({})
const favCurrent = useRef();

const getFavorites = async () => {
    try {
        const value = await AsyncStorage.getItem('favorites')
      if(value !== null) {
        const val = JSON.parse(value)
        favCurrent.current = val
        setIsAsyncLoading(false)
        console.log(favCurrent.current,'favCurrent')  
      }
    } catch(e) {
      // error reading value
    }
}
getFavorites()

// note the console.log above always shows correct, updated list

const { data, loading, error } = useQuery(POSTS_QUERY)

useEffect(() => {
    if (loading) {
        return <Loading/>
    }  
    if (error) {
        return <Text>Error :( </Text>;
    }
    const filterNodes = data?.posts?.data.filter(item => favCurrent.current.includes(item.id));
    setNodes(filterNodes)
    setIsLoading(false)
}, [data]);

if( isLoading || isAsyncLoading ) {
    return (
     // 'Loading...'
    )
} else {
    return (
     // 'List of items...'
    )
}
}

I've also tried a solution from this answer, to no effect:

    const [favData, setFavData] = useState(null)

    useEffect(() => {
        async function getFavorites() {
            setFavData(await AsyncStorage.getItem('favorites'));
        }
        getFavorites()
        setIsAsyncLoading(false)
    }, []);
Rwzr Q
  • 85
  • 1
  • 8

0 Answers0