简体   繁体   中英

How to storage large data in React Native

I have to get a 5MB json file from an API ( https://api.sleeper.app/v1/players/nfl ), but because of his size the fetch take a while, but I just need to get this file once a day . So, my question is: theres a way to storage this file inside my app and get some piece when I have to? I've tried Async Storage and some others packages that uses the same logic, but the async request takes as long as the fetch function .

What I want is some way to manipulate this data in a fast way than if a have to fetch every single time that I need some piece.

Right now I'm using an API made by my own which takes this 5MB file and return the specific piece that I need ( https://teste-draft.netlify.app/.netlify/functions/getplayersdata?name=167 ). But the problem with this temporary solution is when I have to get a lot of players (like 20 or even more), because it's so many requests that the app ends up taking a long time to display the data.

I solved this by creating a Context to store all the 5 MB data, to be fetched when the user open the app. It was not exactly what I wanted, because the fetch run every time when the user close the entire app, but worked...

import { useState, createContext, useEffect } from "react"

export const AllPlayersContext = createContext()

export const AllPlayersContextProvider = ({children}) => {
    const [allPlayers, setAllPlayers] = useState(null)

    const getAllPlayers = () => {
        console.log('Getting players...')
        const URL = `https://api.sleeper.app/v1/players/nfl`;
        fetch(URL)
        .then(response => response.json())
        .then(data => {
            setAllPlayers(data)
        }).catch((e) => {
            console.log('Error:', e)
        })
    }

    useEffect(() => {
        getAllPlayers()
    },[])

    if(!allPlayers){
        return (
          <Loading />
        )
      }


    return ( 
        <AllPlayersContext.Provider value={{allPlayers}}>
        {children}
        </AllPlayersContext.Provider>
     );
}
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM