Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider:

Type '({ children }: { children?: ReactNode; }) => void' is not assignable to type 'FC<{}>'
. Any help would be appreciated.

import React,{FC, useState, useEffect} from 'react'

export interface Coin  {
    id:string;
    name: string;
    current_price: number;
    symbol:string;
    price_change_percentage_24h:number
    image:string;
    market_cap:number
    market_cap_rank:number
}
 export const CoinContext = React.createContext<Coin[] | undefined>(undefined)

 export const CoinProvider:FC= ({children}) => {
    const [loading, setLoading] =useState(false)
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(10);
    const [coinsData, setCoinsData] = useState<Coin[]>([])
  
    const handlePrevPage = () => {
      setPage((prevPage) => prevPage - 1);
    };
  
    const handleNextPage = () => {
      setPage((nextPage) => nextPage + 1);
    };
          
        useEffect(()=>{
         const fetchData= async()=>{
         setLoading(true);
         const response= await fetch(`https://api.coingecko.com/api/v3/coins/markets? 
         vs_currency=usd&order=market_cap_desc&page=${page}&per_page=10&sparkline=false`)
         const result = await response.json()
            setCoinsData(result); 
            setTotalPages(totalPages);
            setLoading(false)
     
        }
            fetchData()
        },[page, totalPages])
  
      
    
      const Coins = coinsData.map((item) => {
        const {
        id, 
        } = item
    return(
    <CoinContext.Provider value={{Coins, totalPages, id, loading, handlePrevPage, handleNextPage, 
      currentPage:{ page }}}>
        {children}
    </CoinContext.Provider>
    )
}

Answer №1

Don't forget to include }) on line 47. The correct logic for that section should be:

const Coins = coinsData.map((item) => item.id)

Answer №2

Ensure that your component includes a return statement.

Verify that you are returning HTML content that can be displayed.


return <>
    {coinsData.map((item) => {
        const { id } = item
        return (
            <CoinContext.Provider value={[{ id: 'id', current_price: 1, image: 'image', market_cap: 0, market_cap_rank: 0, name: 'name', price_change_percentage_24h: 0, symbol: 'symbol' }]}>
                {children}
            </CoinContext.Provider>
        )
    })
    }
</>

Remember to close the map function with a closing parenthesis )

If you only need to pass coinsData

    return <CoinContext.Provider value={...coinsData}>
        {children}
    </CoinContext.Provider>

You have the option to skip the map and simplify your code by destructuring your coinsData directly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Experiencing difficulty accessing my development server at localhost:3000

I recently completed my first React app on my desktop, and after cleaning up my PC due to slowness issues, I encountered an error when trying to run the app again. When I typed "npm start" in the command line, I got the following error message: Error: Ca ...

TypeScript - The key is missing from the type definition, yet it is present in reality

I'm currently working on developing my own XML builder using TypeScript, but I've run into a significant issue: Property 'children' does not exist in type 'XMLNode'. Property 'children' does not exist in type &apos ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...

Choose the specific Element by its dynamicID in JQuery

Just starting out with Jquery and I have a specific task in mind. In my HTML page, I have elements with IDs generated by concatenating a string variable. My goal is to use JQuery to select the element with this dynamically generated ID. See below for more ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

Upon the initial page load, the create-react-app is rendered without any content

I created an app that initially shows a blank page upon startup, but strangely it loads correctly when the page is refreshed. Here is my code: index.js import React from 'react'; import ReactDOM from 'react-dom'; import './Asset ...

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

Utilizing form data binding with multiple instances of forms in React

Parent Component Within my parent component, named Users, there is a snippet of code that includes the functions for adding and updating users: addUser(index, user) { var users = this.state.users var existingUser = users[index] if (existingUse ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

Setting the sidebar width for Nebular with two sidebars in the layout: A step-by-step guide

Having two sidebars (identified as left and right) in my page layout, I initially set both sidebars to a width of 400px using the custom theme method with sidebar-width: 400px. However, I now need to change the width of the right sidebar to 700px. Is the ...

Is there an equivalent concept to Java's `Class<T>` in TypeScript which allows extracting the type of a class constructor?

I'm in need of a feature similar to the Class functionality in Java, but I've had no luck finding it. Class<T> is exactly what I require. I believe it could be named NewableFunction<T>. However, such an option does not exist. Using M ...

What is the best method for sending a user to a different page when a webhook is triggered by an external API in

In my project using NextJS and the pages router, I encounter a scenario where a user initiates a process through a form that takes approximately 30 seconds to complete. This process is carried out by an external API over which I have no control. Once the p ...

Issue encountered when transferring properties to create a search bar

My goal is to create a search input that filters based on the user's input. I have two components - one with the search input (app.js) and the other with the table (table.js). In the search input component (app.js), I can retrieve the current value b ...

What steps can be taken to modify the border color of a Material-UI Box/Tab component to display in black?

I'm currently working on a React app where I am using the Box and Tab component from Material-UI. My goal is to change the border color of the Box component to black while still maintaining its function as a divider. Despite trying to set the borderCo ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Unable to locate '@material-ui/core/Alert'

I encountered an issue while trying to utilize the Alert component from material-ui. Despite successfully installing @material-ui/core, I keep receiving an error stating "Can't resolve '@material-ui/core/Alert'". package.json ''& ...

Determining the Nearest Form to an Element using jQuery

I developed a JavaScript/jQuery script that allows me to check all checkboxes within a form. The function works effectively, but the issue is that it checks all checkboxes on the page regardless of their form wrapper. Here is the function: function toggl ...