ivanichi
ivanichi

Reputation: 49

React Native - Using promises when fetching and returning them to components

i want to display related data on react native, i have 2 response api

response 1

{
"total": 2,
"data" : [
    {
     "date" : "2020-12-01",  
     "time" : "08:00:00"
    },
    {
     "date" : "2020-12-02",     
     "time" : "09:00:00"    
    }
  ]
}

response 2, date is parameter

date : 2020-12-01

{
"total": 2,
"data" : [
  {
   "date" : "2020-12-01",
   "description" : "bla bla bla"
  },
  {
   "date" : "2020-12-01",
   "description" : "vla vla vla"
  }
 ]
}

date : 2020-12-02

{
"total": 1,
"data" : [
  {
   "date" : "2020-12-02",
   "description" : "cla cla cla"
  }
 ]
}

how to use promises on fetch and how components return them, so it can display content descriptions like this

enter image description here

Upvotes: 0

Views: 638

Answers (1)

A McBride
A McBride

Reputation: 405

Are you asking how to use promises with Fetch? Or how to take the results of those promises and use them to create a visual component?

It doesn't look like you've put any work into asking this question and it's quite wide ranging, from setting up components, creating fetch requests to an API and formatting them into visual components.

I'd consider starting here for your fetch request:

https://reactnative.dev/docs/network#making-requests

Then look at how they take the text and place it on a screen here:

https://reactnative.dev/docs/network#making-requests

EDIT: Per the comments below.

You would most likely want to store the results of your request in some form of local state, and pass that state to your FlatList or similar, for instance:

const PromiseExample = () => {
    const [listItems, setListItems] = useState([])
    useEffect(() => {
        async function fetchData() {

            const data = await fetch('localhost:3000/data').json()
            const otherData = await fetch('localhost:3000/otherData').json()

            let joinedData = []

            // at this point you would join your two data structures in whatever way you need to and push the joined data to the var.

            setListItems(joinedData)
        }
    }, [])
    return (
        <FlatList data={listItems} />
    )
}

Upvotes: 1

Related Questions