So the thing I am trying to do is to destructure coinsData, so I can use the id globally and keep the coinsData so I can iterate it somewhere else. Right now I am having a problem with typescript on export CoinProvider Type '({ children }: { children?: ReactNode; }) => void' is not assignable to type 'FC<{}>'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>
)
}
You forgot about }) in line 47.
And logic there should look like this:
const Coins = coinsData.map((item) => item.id)
Your component is missing a return statement.
Make sure to return an HTML that can be rendered.
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>
)
})
}
</>
And, don't forget to close the map function with the parenthesis )
In case, you only want to pass coinsData
return <CoinContext.Provider value={...coinsData}>
{children}
</CoinContext.Provider>
you can renounce the map and simplify your code with destructuring your coinsData directly.
Related
i am trying to query data for dbUser restaurant and basket but im getting error type possible unhandled promise rejection (id:17)
type error: o.userID is not a function. (o.userID('eq', dbUser.id)
type error null is not an object ( evaluating restaurant.id).
type here
import { createContext, useState, useEffect, useContext } from "react";
import { DataStore } from "aws-amplify";
import { Basket, BasketDish } from "../models";
import { useAuthContext } from "./AuthContext";
const BasketContext = createContext({});
const BasketContextProvider = ({ children }) => {
const { dbUser } = useAuthContext();
const [restaurant, setRestaurant] = useState(null);
const [basket, setBasket] = useState(null);
const [basketDishes, setBasketDishes] = useState([]);
const totalPrice = basketDishes.reduce(
(sum, basketDish) => sum + basketDish.quantity * basketDish.Dish.price,
restaurant?.deliveryFee
);
useEffect(() => {
DataStore.query(Basket, (b) =>
b.restaurantID("eq", restaurant.id).userID("eq", dbUser.id)
).then((baskets) => setBasket(baskets[0]));
}, [dbUser, restaurant]);
useEffect(() => {
if (basket) {
DataStore.query(BasketDish, (bd) => bd.basketID("eq", basket.id)).then(
setBasketDishes
);
}
}, [basket]);
const addDishToBasket = async (dish, quantity) => {
// get the existing basket or create a new one
let theBasket = basket || (await createNewBasket());
// create a BasketDish item and save to Datastore
const newDish = await DataStore.save(
new BasketDish({ quantity, Dish: dish, basketID: theBasket.id })
);
setBasketDishes([...basketDishes, newDish]);
};
const createNewBasket = async () => {
const newBasket = await DataStore.save(
new Basket({ userID: dbUser.id, restaurantID: restaurant.id })
);
setBasket(newBasket);
return newBasket;
};
return (
<BasketContext.Provider
value={{
addDishToBasket,
setRestaurant,
restaurant,
basket,
basketDishes,
totalPrice,
}}
>
{children}
</BasketContext.Provider>
);
};
export default BasketContextProvider;
export const useBasketContext = () => useContext(BasketContext);
please help me out. https://www.youtube.com/live/WFo_IxhBxF4?feature=share I'm doing ubereat by Vadim
I've been making a game which at the end, requires the user to type their guess. To avoid confusion in my actual project, I created something in codesandbox which demonstrates the problem I'm having. I should add that the game in codesandbox isn't suppose to make much sense. But essentially you just click any box 5 times which generates a random number and when the component mounts, it also creates an array with 5 random number. At the end, you type a number and it checks if both arrays contain the key entered and colors them accordingly. The problem I'm having is that once the guess component is shown, all the hooks states return to their initial states.
Main.tsx
import { Guess } from "./Guess";
import { useHook } from "./Hook";
import { Loading } from "./Loading";
import "./styles.css";
export const Main = () => {
const {loading, count, handleClick, randArr} = useHook()
return (
<div className="main">
{!loading && count < 5 &&
<div className='click-container'>
{Array.from({length: 5}).fill('').map((_, i: number) =>
<div onClick={handleClick} className='box' key={i}>Click</div>
)}
</div>
}
{loading && <Loading count={count} />}
{!loading && count >= 5 && <Guess arr={randArr} />}
</div>
);
}
Hook.tsx
import { useEffect, useState } from 'react'
export const useHook = () => {
type guessType = {
keyNum: number
isContain: boolean
}
const [disable, setDisable] = useState(true)
const [randArr, setRandArr] = useState<number[]>([])
const [initialArr, setInitialArr] = useState<number[]>([])
const [count, setCount] = useState<number>(0)
const [loading, setLoading] = useState(true)
const [guess, setGuess] = useState<guessType[]>([])
const randomNum = () => {
return Math.floor(Math.random() * (9 - 0 + 1) + 0);
}
useEffect(() => {
const handleInitialArr = () => {
for (let i = 0; i < 5; i++) {
let num = randomNum()
setInitialArr((prev) => [...prev, num])
}
}
handleInitialArr()
}, [])
const handleClick = () => {
if (!disable) {
let num = randomNum()
setRandArr((prev)=> [...prev, num])
setCount((prev) => prev + 1)
setDisable(true)
setLoading(true)
}
}
useEffect(()=> {
const handleLoading = () => {
setTimeout(() => {
setLoading(false)
}, 500)
}
const handleRound = () => {
setDisable(false)
}
handleLoading()
handleRound()
}, [count])
const handleKeyUp = ({key}) => {
const isNumber = /^[0-9]$/i.test(key)
if (isNumber) {
if (randArr.includes(key) && initialArr.includes(key)) {
setGuess((prev) => [...prev, {keyNum: key, isContain: true}])
console.log(' they both have this number')
} else {
setGuess((prev) => [...prev, {keyNum: key, isContain: false}])
console.log(' they both do not contain this number ')
}
}
}
console.log(count)
console.log(randArr, ' this is rand arr')
console.log(initialArr, ' this is initial arr')
return {
count,
loading,
handleClick,
randArr,
handleKeyUp,
guess
}
}
Guess.tsx
import React, { useEffect } from "react";
import { useHook } from "./Hook";
import "./styles.css";
type props = {
arr: number[];
};
export const Guess: React.FC<props> = (props) => {
const { handleKeyUp, guess } = useHook();
useEffect(() => {
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keyup", handleKeyUp);
};
}, [handleKeyUp]);
console.log(props.arr, " this is props arr ");
return (
<div className="content">
<div>
<p>Guesses: </p>
<div className="guess-list">
{guess.map((item: any, i: number) =>
<p key={i} className={guess[i].isContain ? 'guess-num-true': 'guess-num-false'} >{item.keyNum}</p>
)}
</div>
</div>
</div>
);
};
Also, here is the codesandbox if you want to take a look for yourself: https://codesandbox.io/s/guess-numbers-70fss9
Any help would be deeply appreciated!!!
Fixed demo: https://codesandbox.io/s/guess-numbers-fixed-kz3qmw?file=/src/my-context.tsx:1582-2047
You're under the misconception that hooks share state across components. The hook will have a new state for every call of useHook(). To share state you need to use a Context.
type guessType = {
keyNum: number;
isContain: boolean;
};
type MyContextType = {
count: number;
loading: boolean;
handleClick: () => void;
randArr: number[];
handleKeyUp: ({ key: string }) => void;
guess: guessType[];
};
export const MyContext = createContext<MyContextType>(null as any);
export const MyContextProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
// Same stuff as your hook goes here
return (
<MyContext.Provider
value={{ count, loading, handleClick, randArr, handleKeyUp, guess }}
>
{children}
</MyContext.Provider>
);
};
export const App = () => {
return (
<div className="App">
<MyContextProvider>
<Page />
</MyContextProvider>
</div>
);
};
export const Main = () => {
const { loading, count, handleClick, randArr } = useContext(MyContext);
...
}
export const Guess: React.FC<props> = (props) => {
const { handleKeyUp, guess } = useContext(MyContext);
...
}
Your handleKeyUp function is also bugged, a good example of why you need to type your parameters. key is a string, not a number. So the condition will always be false.
const handleKeyUp = ({ key }: {key: string}) => {
const num = parseInt(key);
if (!isNaN(num)) {
if (randArr.includes(num) && initialArr.includes(num)) {
setGuess((prev) => [...prev, { keyNum: num, isContain: true }]);
console.log(" they both have this number");
} else {
setGuess((prev) => [...prev, { keyNum: num, isContain: false }]);
console.log(" they both do not contain this number ");
}
}
};
I am fetching data
I have a brand property and I am trying to display it, and I am trying to implement a click setCurrentSelectedBrand logic to diplay the data of that specific brand[object]. Currently I am getting the TypeError: Cannot read property 'brand' of undefined error in the Main Component, I dont know why
Data
[{
"a_class":[
{
"brand":"A-class",
"id":"1",
"year":"2015"
"price":"12665"
...
"engine_spec":{
...
}
...
}],
"b_class":[
{
"brand":"B-class",
"id":"2",
"year":"2016"
"price":"12665"
...
"engine_spec":{
...
}
...
}],
}
]
Main Component
const Cars = () => {
const { cars, handleSelectBrand} = useContext(CarsContext)
return (
<div>
{Object.keys(cars).map((key:any, index)=>{
let brands:any = cars[key];
return (
<div key={key} onClick={() => handleSelectBrand(key)} className='brand__list' >
{brands[0].brand}
</div>
);})}
<CarsDetails />
</div>
)
}
export default Cars
Context
declare module 'axios' {
export interface AxiosResponse<T = any> extends Promise<T> {}
}
export const CarsProvider:React.FC <IProps> = ({ children } ) => {
const [isLoading, setIsLoading] = useState(false);
const [cars, setCars] =useState< any | ICars[] >([])
const [brands, setBrands] = useState([])
const [currentSelectedBrand, setCurrentSelectedBrand] = useState('')
const handleSelectBrand = React.useCallback((brand) => {
return setCurrentSelectedBrand(cars[brand]);
},[cars])
useEffect(()=>{
const fetchData = async () => {
setIsLoading(true);
const response = await api.get('/cars', {
});
setIsLoading(false)
setCars([...response.data]);
setCurrentSelectedBrand(response[Object.keys(response)[0]]);
console.log(response.data)
};
fetchData()
},[brands, cars])
I have some JSON that is formatted like this:
{
card_id: "afe1500653ec682b3ce7e0b9f39bed89",
name: "A.J. Burnett",
playerattribute: {
team: "Marlins",
rarity: "Diamond",
}
}
I'm attempting to display the name and the team in a component. Here is what I have.
const PlayerProfile = ({ match, location }) => {
const { params: { cardId } } = match;
const [player, setPlayer] = useState(0);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
`http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
).then((result) => {
setPlayer(result.data);
});
};
fetchData();
}, []);
return (
<Container component="main">
Name: {player.name}
Team: {player.playerattribute.team}
</Container>
)
}
export default PlayerProfile;
However, I get this error: TypeError: Cannot read property 'team' of undefined
The name works fine. So I'm assuming it's an issue with the nested JSON.
You probably shouldn't instanciate your player state with 0 if the projected value is an object.
The error comes up because you try to access a property of an object property that doesn't exist at creation.
Basically, your code tries to do this: {0.playerattribute.team}
0.playerattribute => undefined
Workaround would be a conditionnal render or a default initial value of your state that matches the JSX needs.
const PlayerProfile = ({ match, location }) => {
const { params: { cardId } } = match;
const [player, setPlayer] = useState({
name: "",
playerattribute: {
team: ""
}
});
useEffect(() => {
const fetchData = async () => {
const result = await axios(
`http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
).then((result) => {
setPlayer(result.data);
});
};
fetchData();
}, []);
return (
<Container component="main">
Name: {player.name}
Team: {player.playerattribute.team}
</Container>
)
}
export default PlayerProfile;
or
const PlayerProfile = ({ match, location }) => {
const { params: { cardId } } = match;
const [player, setPlayer] = useState(null);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
`http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
).then((result) => {
setPlayer(result.data);
});
};
fetchData();
}, []);
return (
<Container component="main">
Name: {player?.name}
Team: {player?.playerattribute?.team}
</Container>
)
}
export default PlayerProfile;
Set useState const [player, setPlayer] = useState("");
const [player, setPlayer] = useState({
Name: '',
Team: ''
}}
//on your setPlayer you may
const playerData = result.data;
setPlayer({
Name: playerData.name
Team: playerData.playerattribute.team})
if you still getting same error, please provide screenshot of console.log(result)
Summarize the problem
I have a page within a Gatsby JS site that accepts state via a provider, and some of that activity is able to be used, however, I am unable to provide the contents from a mapping function that is given via context.
Expected result: the expected elements from the mapping function would render
Actual result: the elements in question are not rendered
No error messages
Describe what you've tried
I thought the issue was not explicitly entering in return on the arrow function in question, but that does not change any of the output
Also, rather than try to access the method directly on the page (via a context provider) I moved the method directly into the Provider hook. This did not change any of the rendering.
Show some code
here is Provider.js
import React, { useState, useEffect } from 'react';
import he from 'he';
export const myContext = React.createContext();
const Provider = props => {
const [state, setState] = useState({
loading: true,
error: false,
data: [],
});
const [page, setPage] = useState(1);
const [score, setScore] = useState(0);
const [correctAnswers, setCorrectAnswers] = useState([]);
const [allQuestions, setAllQuestions] = useState([]);
const [answers, setAnswers] = useState([]);
const [right, setRight] = useState([]);
const [wrong, setWrong] = useState([]);
function clearScore() {
updatedScore = 0;
}
function clearRights() {
while (rights.length > 0) {
rights.pop();
}
}
function clearWrongs() {
while (wrongs.length > 0) {
wrongs.pop();
}
}
let updatedScore = 0;
let rights = [];
let wrongs = [];
const calcScore = (x, y) => {
for (let i = 0; i < 10; i++) {
if (x[i] === y[i]) {
updatedScore = updatedScore + 1;
rights.push(i);
} else wrongs.push(i);
}
}
useEffect(() => {
fetch('https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean')
.then(response => {
return response.json()
})
.then(json => {
const correctAnswer = json.results.map(q => q['correct_answer']);
const questionBulk = json.results.map(q => q['question']);
setState({
data: json.results,
loading: false,
error: false,
});
setCorrectAnswers(correctAnswers.concat(correctAnswer));
setAllQuestions(allQuestions.concat(questionBulk));
})
.catch(err => {
setState({error: err})
})
}, [])
return (
<myContext.Provider
value={{
state, page, score, answers, right, wrong,
hitTrue: () => {setAnswers(answers.concat('True')); setPage(page + 1);},
hitFalse: () => {setAnswers(answers.concat('False')); setPage(page + 1);},
resetAll: () => {
setAnswers([]);
setPage(1);
setScore(0);
setRight([]);
setWrong([]);
clearScore();
clearWrongs();
clearRights();
},
calculateScore: () => calcScore(answers, correctAnswers),
updateScore: () => setScore(score + updatedScore),
updateRight: () => setRight(right.concat(rights)),
updateWrong: () => setWrong(wrong.concat(wrongs)),
showRightAnswers: () => {right.map((result, index) => {
return (
<p className="text-green-300 text-sm" key={index}>
+ {he.decode(`${allQuestions[result]}`)}
</p>)
})},
showWrongAnswers: () => {wrong.map((result, index) => {
return (
<p className="text-red-500 text-sm" key={index}>
- {he.decode(`${allQuestions[result]}`)}
</p>
)
})},
}}
>
{props.children}
</myContext.Provider>
);
}
export default ({ element }) => (
<Provider>
{element}
</Provider>
);
^the showRightAnswers() and showWrongAnswers() methods are the ones I am trying to figure out
and here is the results.js page.{context.showRightAnswers()} and {context.showWrongAnswers()} are where the mapped content is supposed to appear.
import React from 'react';
import Button from '../components/Button';
import { navigate } from 'gatsby';
import { myContext } from '../hooks/Provider';
const ResultsPage = () => {
return (
<myContext.Consumer>
{context => (
<>
<h1 className="">You Finished!</h1>
<p className="">Your score was {context.score}/10</p>
{context.showRightAnswers()}
{context.showWrongAnswers()}
<Button
buttonText="Try Again?"
buttonActions={() => {
context.resetAll();
navigate('/');
}}
/>
</>
)}
</myContext.Consumer>
);
}
export default ResultsPage;
You are returning inside your map, but you're not returning the map call itself - .map returns an array, and you have to return that array from your "show" functions, e.g.
showWrongAnswers: () => { return wrong.map((result, index) ...
^^^^
This will return the array .map generated from the showWrongAnswers function when it's called, and thus {context.showWrongAnswers()} will render that returned array