Bilen
Bilen

Reputation: 1

I am trying to use useContext to give access of the api data from one component to other but i am failing to do so

I created a component in which i requested the data from rapid api. After that i got the coin summary in coinRanking after that i am trying to pass data in homePage but i couldn't. Please help me with sharing data using useContext.

import React, { useState } from 'react'
import { useQuery } from "react-query"
import axios from 'axios'
import { createContext } from 'react';
import HomePage from '../Pages/HomePage';

const options = {
  method: 'GET',
  url: 'https://coinranking1.p.rapidapi.com/coins',
  params: {
    referenceCurrencyUuid: 'yhjMzLPhuIDl',
    timePeriod: '24h',
    'tiers[0]': '1',
    orderBy: 'marketCap',
    orderDirection: 'desc',
    limit: '50',
    offset: '0'
  },
  headers: {
    'X-RapidAPI-Key': 'ea3e0e9305msh25681129077648ep1f06f9jsnb2ee8da018dc',
    'X-RapidAPI-Host': 'coinranking1.p.rapidapi.com'
  }
};

const DataContext = createContext({coinRanking}) // i don't know what to pass over here.

function QueryData({children}) {
  const getData = axios.request(options)
  const {data, isLoading, isError, error, isFetching} = useQuery("getData", ()=>getData,{})
  
  if (isLoading){
    console.log("Loading");
    return <p>Loading</p>
  } else if (isError){
    console.log("error");
    return <p>{error}</p>
  }

  const coinRanking= data?.data?.data.stats

  return (
    <div>
      <DataContext.Provider value={{coinRanking}}> //i am trying to pass coinRanking in Homepage
        <HomePage/>
      </DataContext.Provider>
    </div>
  )
}

export default DataContext

Upvotes: 0

Views: 213

Answers (1)

Bilen
Bilen

Reputation: 1

Well, i spent too much time on finding the answer on my own and watching and exploring lots of video and documentation. Finally, i got an answer where i was but due to minor error i thought this is not doable. However, i was wrong. I tried again and it is working...

import React, { useState } from 'react'
import { useQuery } from "react-query"
import axios from 'axios'
import { createContext } from 'react';
import HomePage from '../Pages/HomePage';

const options = {
  method: 'GET',
  url: 'https://coinranking1.p.rapidapi.com/coins',
  params: {
    referenceCurrencyUuid: 'yhjMzLPhuIDl',
    timePeriod: '24h',
    'tiers[0]': '1',
    orderBy: 'marketCap',
    orderDirection: 'desc',
    limit: '50',
    offset: '0'
  },
  headers: {
    'X-RapidAPI-Key': 'ea3e0e9305msh25681129077648ep1f06f9jsnb2ee8da018dc',
    'X-RapidAPI-Host': 'coinranking1.p.rapidapi.com'
  }
};

export const DataContext = createContext() //i am trying to pass data through this context

function QueryProvider({children}) {
  const getData = axios.request(options)
  const {data, isLoading, isError, error, isFetching} = useQuery("getData", ()=>getData,{})
  
  if (isLoading){
    console.log("Loading");
    return <p>Loading</p>
  } else if (isError){
    console.log("error");
    return <p>{error}</p>
  }

  const coinRanking= data?.data?.data.stats
  
  return (
    <div>
      {
        Object.entries(coinRanking).map(([key, value], i)=>{
          console.log("this is value");
          return(
            <>
              <p>Hi, i am data</p>
              <p key={i}>{key}--{value}</p>
            </>
          )
        })
      }
      <DataContext.Provider value={{coinRanking}}>
        {children}
      </DataContext.Provider>
    </div>
  )
}

export default QueryProvider

and for Home page

import React from 'react'
import {DataContext} from '../DataQuery/dataQuery'
import { useContext } from 'react'

const HomePage = (props) => {
  const {coinRanking} = useContext(DataContext)
  console.log(coinRanking, "is in the homepage")
  return (
    <div>
        <div>HomePage</div>
    </div>
  )
}

export default HomePage

most important is the app.js file where you have to use context provider with router

import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { QueryClientProvider, QueryClient } from "react-query"
import './App.css'
import HomePage from './components/Pages/HomePage'
import QueryProvider,{DataContext} from './components/DataQuery/dataQuery'
import { ReactQueryDevtools } from 'react-query/devtools'

const queryClient = new QueryClient()

function App() {
  return (
    <div>
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
        <QueryProvider>
          <Routes>
            <Route path="/" element={<HomePage/>}></Route>
          </Routes>
        </QueryProvider>
        </BrowserRouter>
        {/* <ReactQueryDevtools initialIsOpen={false} position="bottom-right"/> */}
      </QueryClientProvider>
    </div>
  )
}

export default App

Upvotes: 0

Related Questions